7

How Shells Work: The cd Builtin Command

 3 years ago
source link: https://www.growingwiththeweb.com/2019/07/how-shells-work-cd.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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$ _

Resolving symlinks#

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#

Share this page#

More posts tagged Terminal#


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK