Growing with the Web

How Shells Work: The cd Builtin Command

Published
Tags:

I’m currently going through the POSIX specification and wanted to document some of the lesser known things you can do.

The cd command is a shell “builtin”, meaning it isn’t a program on disk but something built into the shell itself.

Go to the home directory

Simply running cd without any arguments is equivalent to cd ~ which goes to the $HOME directory.

~/foo$ cd
~$ _

Go to the previous directory

cd - will go to the previous directory, specifically $OLDPWD which gets updated on a successful cd. It will also print the directory when this happens.

~$ cd foo
~/foo$ cd -
/home/daniel/foo
~$ _

Make directories more accessible via $CDPATH

The $CDPATH environment variable allows specifying paths to check if the directory exists within, before checking the current directory. It will also print the directory when this happens.

~$ mkdir -p foo/bar
~$ cd bar
cd: bar: No such file or directory
~$ export CDPATH=~/foo
~$ cd bar
/home/daniel/foo/bar
~/foo/bar$ _

As you might have guessed, just like $PATH you can use multiple paths separated by : that will be checked in order:

~$ mkdir -p foo/bar b
~$ export CDPATH=.:~/foo # check the current directory first
~$ cd bar
/home/daniel/bar
~/bar$ _

Normally when navigating to a symlink directory the path will remain as the symlink name:

~$ mkdir real
~$ ln -s real fake
~$ cd fake
~/fake$ _

You can force symlinks to be resolved via the -P option:

~$ cd -P fake
~/real$ _

The opposite of this option is -L which is the default. Since it is the default, the only reason I can think of why you would want to use it is if you have an alias to change the default to -P:

~$ alias cd='cd -P'
~$ cd fake
~/real$ cd -L ../fake
~/fake$ _

References

Like this article?
Subscribe for more!