Navigation basics

Linux commands: cd

Learn how the Linux cd command changes the directory you are in, using a folder name, the .. parent and . current shortcuts, or an absolute path from /.

Once you have a folder, you can move into it using the cd command. cd means change directory. You invoke it specifying a folder to move into. You can specify a folder name, or an entire path.

Example:

mkdir fruits
cd fruits

Now you are inside the fruits folder. Run pwd and you’ll see the path ends with /fruits.

You can use the .. special path to indicate the parent folder:

cd .. #back to the home folder

The # character starts a comment, which lasts until the end of the line. The shell ignores everything after it. I use comments here to explain what each line does, but you don’t need to type them.

You can use .. to form a path:

mkdir fruits
mkdir cars
cd fruits
cd ../cars

../cars means “go up one level, then into cars”. You moved from fruits to its sibling folder in one step.

There is another special path indicator, ., which indicates the current folder. You’ll rarely type cd . on its own, but . shows up everywhere in paths, like ./script.sh.

You can also use absolute paths, which start from the root folder /:

cd /etc

An absolute path works from anywhere, because it doesn’t depend on where you are now. A relative path like cars only works if cars is inside the current folder.

Two shortcuts I use constantly. cd with no argument brings you back to your home folder, wherever you are:

cd

And cd - brings you back to the previous folder you were in. Very handy when you jump somewhere to check one thing and want to come straight back.

If the folder doesn’t exist, cd tells you. This is what Bash prints:

cd fruitz
bash: cd: fruitz: No such file or directory

Nothing changed: you’re still in the same folder. Nine times out of ten it’s a typo, like the one above. The other case is being in a different folder than you think. ls shows you what’s actually here, and pwd shows you where “here” is.

One thing that surprises beginners: cd is case sensitive on Linux. cd Documents and cd documents are two different folders. macOS is more forgiving by default, but don’t rely on it, because the same command will fail the moment you run it on a Linux server.

This command works on Linux, macOS, WSL, and anywhere you have a UNIX environment

Lesson completed