Bash – Symbolic link to change directory only works from home dir

bashcd-commandsymlink

Using this answer, I have created a symbolic link in my .bashrc file to make changing to a frequently used directory easier.

E.g.

ln -s ~/a/b/c/d/development dev

I can change directory from my home dir to the development dir by entering cd dev. I can also enter ls dev from my home dir and that works too.

However, these commands only work in my home dir. If I enter them from anywhere else I get an error telling me No such file or directory.

If I enter cd ~/dev or ls ~/dev it works.

Can someone explain why that is and how I can fix it so I don't have to include ~/ in the path when I'm not in my home dir.

Best Answer

Since you’re using Bash as your shell, you can use the CDPATH shell variable. The Bash manual describes it as

a search path: each directory name in CDPATH is searched for directory, with alternative directory names in CDPATH separated by a colon (‘:’)

You could add the following line to your .bashrc:

CDPATH=".:$HOME"

If you later type cd dev, the current working directory would be searched for a sub-directory named dev:

  • If such a directory exists, it changes into that directory (as the cd builtin command usually works).
  • If not, it would then search your home directory (~), find the symbolic link (realise that it’s a link to a directory) and change to the target directory (pointed to by ~/dev).

If you wanted to give preference to the directories within your home directory, you could list $HOME first in your CDPATH ("$HOME:.") but I would strongly advise against that as it breaks the principle of least surprise: the resulting behaviour differs too greatly from the standard.

Related Question