Skip to content

cd

Changes the current directory.

cd output

Syntax

cd [OPTION] [DIRECTORY]

Options

Option / argument Description
(none) or ~ Go to your home directory
- Go back to the previous directory and print its path
.. Go one level up
~USER Go to the home directory of USER
-L Follow symbolic links logically (default)
-P Resolve symbolic links and go to the physical directory

Examples

Change to an absolute path:

cd /etc/ssh
pwd
/etc/ssh

Go one level up:

cd ..
pwd
/etc

Jump back to the previous directory:

cd /var/log
cd -
/etc

Go back to your home directory:

cd
pwd
/home/nox

Go to the home directory of another user:

cd ~www-data
pwd
/var/www

Try to enter a directory without permission:

cd /root
-bash: cd: /root: Permission denied

When do I need it?

  • All the time: to get to configuration files (/etc), logs (/var/log) or web content (/var/www)
  • To switch quickly between two directories with cd -, for example between a config directory and its log directory
  • In scripts, to work in a fixed directory before running further commands

Use Tab completion

Type the first letters of a directory and press Tab. Bash completes the name, and pressing Tab twice shows all matches. This saves typing and avoids typos.

Help for cd

cd is built into the shell, so there is no man cd. Use help cd instead.

cd in scripts: always check the result

If cd fails, the script keeps running in the old directory. Combined with rm, this can delete the wrong files. Always stop the script if cd fails:

cd /var/www/example.com/cache || exit 1
rm -rf ./*

pwd · ls · pushd