cd

2024-10-25

Understanding the Basics

The cd command’s primary function is simple: to change your current working directory. Your working directory is the location from which the shell executes commands. If you type ls (list files), it will show you the contents of your current working directory.

The most basic usage involves specifying the target directory path:

cd /home/user/documents

This command changes your working directory to the /home/user/documents directory. Note the forward slash / as the path separator in Linux.

If you omit the path, cd defaults to your home directory:

cd

This is equivalent to:

cd ~

The ~ symbol is a shorthand for your home directory.

Relative vs. Absolute Paths

cd can use both relative and absolute paths.

Let’s illustrate with examples:

Suppose your current directory is /home/user:

Command Result
cd documents Changes to /home/user/documents
cd ../ Changes to /home
cd /tmp Changes to /tmp
cd ./reports Changes to /home/user/reports (if reports exists)

.. represents the parent directory. . represents the current directory. These are very useful for navigating up and down the directory tree.

Advanced Usage

cd offers some more advanced features:

cd $MYDOCS
mkdir -p /tmp/my/new/directory && cd /tmp/my/new/directory

The -p option ensures that parent directories are also created if they don’t exist.

Practical Examples in Scripts

The cd command is indispensable in shell scripts for navigating to various locations before executing other commands:

#!/bin/bash


cd /home/user/projects/myproject


./build.sh


cd ~

This script demonstrates changing to a project directory, executing a build script, and returning to the home directory afterwards, maintaining a structured and organized workflow. This is vital for ensuring scripts execute in the correct context.