I am experimenting with symbolic links and I'm encountering a couple issues. The first is how after following a symbolic link to a directory to display the actual working directory instead of the directory with respect to the symbolic link (when using pwd, for instance). The second is how to "back up" into the actual directory in the file system instead of backing into the symbolic link.


From man pwd on my Ubuntu:

your shell may have its own version of pwd

I use bash. Simple pwd command gives me a path with respect to the symbolic link; yet /bin/pwd returns the actual path. The cd command is also a bash builtin.

In other words: this is shell specific.

EDIT: thrig's comment (see below) seems to be a better alternative to everything I wrote below this line.

To "back up" into the actual directory try cd "$(/bin/pwd)/.." or cd "$(/bin/pwd)"; cd ... The second form may be tweaked to build an alias to cd, I think:

alias cd='cd "$(/bin/pwd)"; cd'

In the similar way you can get rid of bash pwd builtin:

alias pwd=`/bin/pwd`
  • 2
    The bash option set -o physical is relevant here. – thrig May 3 '16 at 22:44
  • 1
    @thrig Make it an answer and get credit. Your way seems to be the right way. – Kamil Maciorowski May 3 '16 at 23:03
  • This is very interesting. Can you explain what's going on with pwd? I would expect it to have the same behavior as /bin/pwd. – dsaxton May 3 '16 at 23:35
  • Also, am I mistaken or does set -o physical handle the pwd issue too? – dsaxton May 3 '16 at 23:40
  • My shell (bash) has pwd builtin which has precedence over /bin/pwd binary. The binary is never executed by pwd command, because the shell does all the work by itself and does it its own way. After set -o physical the way is somewhat different. – Kamil Maciorowski May 3 '16 at 23:57

What you want is pwd -P.

From man pwd on CentOS 6:

   -L, --logical
          use PWD from environment, even if it contains symlinks

   -P, --physical
          avoid all symlinks

Or, from the BSD pwd man page and slightly more helpfully worded:

 -L      Display the logical current working directory.

 -P      Display the physical current working directory (all symbolic
         links resolved).

I'm not 100% sure what you mean by "back up," but assuming you mean "Change directories into the parent of the current directory," you can use:

cd "$(dirname "$(pwd -P)")"

Which is equivalent to cd .. if your current working path includes no symlinks.

Alternatively, you could use cd "$(pwd -P)" to go to the physical path of the current logical directory, and then use cd .. as desired.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.