Get current path when in a symbolic linked directory

155 Views Asked by At

When I am in a symbolic liked directory (ln -s ...) and invoke Ruby's Dir.pwd it returns the path of the target directory. I need a way to return the link directory like Linux's pwd do. The following script exemplify my need:

#!/bin/bash

set -u
set -e

rm -rf '/tmp/root_dir'
mkdir -p '/tmp/root_dir'

mkdir '/tmp/root_dir/target_dir'
ln -s '/tmp/root_dir/target_dir' '/tmp/root_dir/symlink_dir'

echo "== Printing Linux PWD =="
(cd '/tmp/root_dir/symlink_dir'; pwd)

echo "== Printing Ruby version =="
ruby --version

echo "== Printing IRB version =="
irb --version

echo "== Printing Ruby PWD =="
(cd '/tmp/root_dir/symlink_dir'; echo  'puts ::Dir.pwd' | irb --noecho --noverbose)

echo "=== Running command \"pwd\" in Ruby ==="
(cd '/tmp/root_dir/symlink_dir'; echo  'system("pwd")' | irb --noecho --noverbose)

Output:

/tmp/root_dir/symlink_dir
== Printing Ruby version ==
ruby 2.7.4p191 (2021-07-07 revision a21a3b7d23) [x86_64-linux]
== Printing IRB version ==
irb 1.2.6 (2020-09-14)
== Printing Ruby PWD ==
/tmp/root_dir/target_dir
=== Running command "pwd" in Ruby ===
/tmp/root_dir/target_dir

How can I get the symbolic link path as the current path instead of target path using Ruby?


Edit 1: added result for system('pwd') executed in Ruby.

2

There are 2 best solutions below

2
MohamedSamny On

Do you think using system('pwd') would be sufficient?

It definitely will give you the result you are after. But it looks like a hackish solution for me!

0
Eduardo Henrique Bogoni On

I went with:

ENV['PWD'] || ::Dir.pwd

I got no other way to get the link directory in Linux than getting the value of environment variable PWD. When is not present (Other plataforms?) it uses the default way to get current directory in Ruby.