Linux

How the cd command works in Linux

Sponsor

The cd command in linux stands for change directory, and is used to change directory when you have a terminal window open. It's used frequently, so it is useful to know.

The syntax for the cd command looks like this:

cd [OPTIONS] directory

How the cd command works

At its most basic, when we open a new terminal window, we can use cd to navigate between directories. Suppose we are in Documents, and there is a subfolder called Project. If we want to move into the Project folder, we would type the following:

cd Project

And if we want to move back up to documents, we can use ../ - so assuming we are in now in Project, the following command will bring us back to the Documents directory:

cd ../

Using Relative Path Names with cd in Linux

While ../ refers to the directory one level above, ./ refers to the current directory. As such, if we are in Documents and want to move to Project again, the following command will also work:

cd ./Project

We can also string ../ together - so the following will move two directories up:

cd ../../

How to navigate to the home directory in Linux

If you want to navigate to the home directory in linux, we have to use the cd command along with a tilde, or ~.

As such, the following command will navigate us to the home directory:

cd ~

We can also navigate to directories within the home directory by following it with a slash, so the following will move us into a folder called Project within our home directory:

cd ~/Project

Options for the cd command in Linux

There are two options available to the cd command which we can mention straight after we type cd. These are:

  • -L - which is by default enabled, and ensures recognition of symlinks within linux.
  • -P - which does the opposite of -L and ignores symlinks.

What are symlinks?

Symlinks or symbolic links are virtual folders. They link to other folders in other directories. If we use -P with cd, then symlinks are ignored.

An example of a cd command with symlinks disabled looks like this:

cd -P ~/Project
Last Updated Friday, 4 March 2022
Johnny Simpson
Johnny Simpson

Subscribe for Daily Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email