Skip to content

Let us talk about cd (change directory)

CD Command Line Cover

The cd command is probably the most used Linux command (there is not a definite answer out there in the wild and wide expanses of the internet). It stands for ‘change directory‘ (of course), and is fundamental and indispensable to everyone who at least knows how to open a terminal window. So, I’ve decided to kinda do the basics on the cd command in this article, what it does, how it works and how can you do some nice hacky stuff with it.

What is the cd command?

The cd command is a built-in shell command that allows users to change their current working directory. A shell command is a function called from the shell which is also executed in the shell itself, instead of an external executable. A shell is… a Unix-based interpreter that provides the command line interface for us to use. An interpreter is… well, this is too low-level to know for the topic at hand, so we’ll ignore it. We need cd in Linux systems because we are interacting with the computer that runs a Linux or Unix-like system primarily through the command line interface (CLI). We can use cd to traverse the directory tree, move between different directories, and access files.

The following is the cd syntax:

cd [option] <directory>

On a deeper level cd works as follows. Unix-like operating systems have a current working directory for every running process. The directory serves as the reference point for any relative file system operations that the process may perform. When we run a command, it starts in the context of the current working directory, which then can be changed using the cd command. By running cd we trigger a state change in the running process. The kernel will execute this state change by running the system call chdir (change directory) and set the new working directory for the process. The cd command takes one or more arguments, which are actually directory paths. We could use absolute paths from the working directory (/var/ftp/pub) or relative paths from our current directory (.../music). If we don’t provide the argument cd will default to the home directory. It will check and validate the provided directory path, by checking whether the directory exists, whether the process has permission to access and, and if there are any errors in the process. If errors are found cd reports an error and doesn’t change the working directory.

Some of the most common uses of cd are following:

Navigating the File System

The most basic and fundamental use of the cd command. We can utilize it to navigate the file system by moving to a specific directory. The following command changes your working directory to /documents/Invoices:

cd /documents/Invoices
Returning to the Home Directory

Also, a common use, with this command we return to our home directory. Simply typing cd without any arguments is enough. An alternative way to achieve the same thing is typing cd with Tilda (~).

cd
cd ~

Keep in mind that you can change the base directory by using the command export CDPATH=.:~:/etc:/var. When the CDPATH variable is set, you create a search path of directories that cd will look through to find the directory you specified. This can make navigation more convenient, especially in complex directory structures.

Moving to the Parent Directory

We also need a way to move up one level in the directory hierarchy, for this we’ll use .. as the cd argument.

cd ..
Using Relative Paths

You can use relative paths to navigate the file system. For example, to move to a subdirectory of your current location.

cd documents/my_folder
Using Absolute Paths

The difference between absolute and relative paths is that absolute paths begin with the root directory -> /. The absolute pathname is the path from the root directory to the directory we want to navigate to. When is a good use case for absolute paths? Let us say we are deep into a directory searching for something and we realize, oh we should go to a completely different directory. Instead of repeating .. to go to the parent directory, we could just write something like this:

cd /var/ftp/pub
Auto-Completion

A helpful feature, autocompletion can save time, and reduce the chance of making typos. We can trigger it by typing just a part of the directory name and pressing the ‘Tab‘ key.

Using Environment Variables

You can use environment variables in the cd command, making it more versatile. The following snippet would navigate us to our home directory (if the home directory variable exists, hint: it should).

cd $HOME

Tips and tricks

Credit where credit is due. Some of these tricks were inspired by the hacks from thegeekstuff website. If you haven’t please visit the site for amazing Linux tips.

Using an alias

You may find yourself frequently moving up the directory hierarchy to access parent directories. While the trusty cd .. command does the job, there’s a more efficient way to achieve this – by creating aliases for cd commands.

In the context of a command-line interface, an alias is a custom-made shortcut or abbreviation for a longer command. We create aliases to make our workload more efficient and faster. When it comes to cd commands, you can create custom aliases that allow you to move up the directory tree with a single, easy-to-remember shortcut.

Generally in Bash, you can add aliases to your ~/.bashrc file. Open it with a text editor and add the following lines to create an alias for moving up one directory level:

alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."

cd ..
cd ...
cd ....

The first line sets up an alias to move up one directory, the second for moving up two directories, and so on. You can add as many aliases as you want. To reiterate .. takes you up one directory, ... takes you up two directories, .... takes you up three directories, and you can go to infinity.

There are alternatives to the method above. For example using the numbering methodology.

alias ..="cd .."
alias ..2="cd ../.."
alias ..3="cd ../../.."

cd ..
cd ..2
cd ..3
alias cd1="cd .."
alias cd2="cd ../.."
alias cd3="cd ../../.."

cd cd1
cd cd2
cd cd3

Create a new directory and cd using a single command

In Linux, you can use a combination of commands and operators to perform both mkdir (make directory) and cd (change directory) in a single command. This can be achieved using command chaining with the && operator. Here’s an example:

mkdir new_directory && cd new_directory

The alternative to combining both mkdir and cd into one command by changing the .bash_profile, and adding the following function

code .bash_profile

function mcd() {
    mkdir "$1" && cd "$1"
}

Toggling between the last two directories

Toggling between the last two directories in Linux using the cd - command is a simple and convenient way to switch back and forth between two locations in the file system. Here’s a step-by-step guide on how to achieve this:

# Navigate to the first directory
cd /path/to/first_directory

# Navigate to the second directory
cd /path/to/second_directory

# Toggle between the last two directories
cd -  # Toggles to /path/to/first_directory
cd -  # Toggles back to /path/to/second_directory

Now, you can use the cd - command to toggle between the last two directories you visited. This command automatically switches to the previous directory.

Using find and cd together

We initiate a search starting from the /path/to/search directory, and we look for files based on the -type f option. We search for a file named filename in the /path/to/search directory, and its subdirectories. Next, we come to the -exec dirname {} \; option that will extract the directory part of the file’s path for every file found by find. Then, when we have found a path the cd command will change the current working directory to the path found.

cd "$(find /path/to/search -type f -name "filename" -exec dirname {} \;)"

Navigate to the Newest Subdirectory

Below we have the command that will change the directory to the latest modified subdirectory. With ls -td -- */ we list all directories, sorting them by modification time, with the newest first. The output is then taken to the pipe, head -n 1 which prints only the first line of the output (in our case it will print the most recently modified directory). Then with cd "$( ... )" we substitute the output and change the working directory to the captured path.

cd "$(ls -td -- */ | head -n 1)"

Conclusion

In essence, with cd we can explore the file system, access files, and in combination with other commands we can even manipulate data and control environments. In the end, it is not a simple/basic command; it is an important system call that handles processes and their interaction with the file system.