98

I have my code mounted as an sshfs in my home directory, but the hierarchy is difficult to remember, so I created a symlink in my home directory leading to that directory. Is there a way so that when I cd to that symbolic link, instead of cding to the symbolic link, it will actually cd to that directory?

If the question was unclear, here is an example of what I am looking for:

foo@foo:~$ ls -l
lrwxrwxrwx  1 foo      foo              5 2012-11-14 08:20 foo -> bar/bar

foo@foo:~$ cd foo
foo@foo:~/bar/bar/$
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
rowantran
  • 1,805
  • 2
  • 13
  • 7
  • 3
    two [related](http://unix.stackexchange.com/questions/36319/symbolic-link-to-a-directory-and-relative-path) [questions](http://unix.stackexchange.com/questions/11044/changing-parent-directory-with-symlinks) – jw013 Nov 14 '12 at 16:32

1 Answers1

138

With any POSIX implementation of cd, you can use the -P option to do this.

$ help cd
...
    -P      use the physical directory structure without following symbolic links
...

You can see it in action here:

$ mkdir foo
$ ln -s foo bar
$ cd -P bar
$ pwd
/tmp/tmp.WkupF2Ucuh/foo

If you want this to be the default behaviour, you can either create an alias for cd, like so:

alias cd='cd -P'

...or use set -o physical. For tcsh, the equivalent command is set symlinks=chase.

Chris Down
  • 122,090
  • 24
  • 265
  • 262
  • 1
    And if you don't have a Posix implementation...? – SMBiggs May 18 '19 at 01:53
  • 2
    You do have a POSIX implementation. POSIX is a standard base, somethings are added on top or changed a bit, "With any POSIX implementation" means this will work almost anywhere, i.e. its not something bash or ksh specific. – teknopaul Jan 29 '20 at 10:21
  • zsh note: `set CHASELINKS` is equivalent to `set -o physical` (which I believe is for backward compatibilty with bash). – Sridhar Sarnobat Jan 04 '23 at 23:03