Linux cd Command: Change the Current Directory

cd is a command in the Linux shell that changes the current working directory. You can move using an absolute or relative path, move to the home directory without arguments, or return to the previous directory with cd -.

cd is a shell built-in command because it needs to change the state of the current shell, not an external executable. This article explains path navigation, symbolic link handling, CDPATH, and safe usage in scripts, based on Bash.

What is the cd command?

cd stands for change directory and changes the shell's current working directory. Commands executed afterward with relative paths search for files and directories based on the changed directory.

You can check the current location with pwd.

pwd
cd /var/log
pwd

By running type cd, you can confirm that it is a Bash built-in command. If executed as a separate program, only the child process’s directory changes and it cannot affect the parent shell, so the shell implements it directly.

Basic Syntax

cd [-L] [-@] [directory]
cd -P [-e] [-@] [directory]

Generally, you only need to specify the directory to move to.

cd /etc
cd projects

If the move is successful, it returns an exit status of 0, and if the path does not exist or there are insufficient permissions, it returns a non-zero value. In scripts where success is important, you should check the exit status.

Moving with Absolute and Relative Paths

Using Absolute Paths

An absolute path starting from the root directory / points to the same target regardless of the current location.

cd /var/log
cd /usr/local/bin
cd /

Absolute paths are easier to understand if the base location needs to be clear in operating procedures or scripts.

Using Relative Paths

Relative paths are interpreted based on the current working directory.

cd documents
cd projects/web
cd ../backup

The same command may move to a different directory or fail depending on the current location when executed. If the location before and after moving is important, check with pwd.

Moving to Home, Parent, and Previous Directories

Moving to the Home Directory

If you run cd without arguments, you move to the user's home directory specified by the HOME variable. Using tilde expansion with cd ~ usually has the same result.

cd
cd ~
cd ~/Downloads

The home directory of another user can be referenced as ~username according to the system account information.

cd ~alice

You cannot move to it if the user does not exist or if you do not have permission to access the home path.

Representing Current and Parent Directories

A single dot . represents the current directory, and two dots .. represent the parent directory.

cd .
cd ..
cd ../..
cd ../../shared

cd. usually does not change your location. To move up several levels, use ../ for each step. Interpreting three dots ... as two levels up is not standard Bash behavior.

Returning to the Previous Directory with cd -

cd - moves to the previous working directory stored in OLDPWD and, if successful, prints the new path.

cd /etc
cd /var/log
cd -

It is convenient when alternating between two directories. If the previous directory information has not yet been created in the current shell, an OLDPWD not set error may occur.

Paths with spaces and special characters

Enclose paths in quotes

Paths with spaces should be enclosed in quotes so that they are passed as a single argument.

cd "Project Files"
cd '/srv/shared data'

When using a variable as a path, it is also safe to enclose it in double quotes to prevent the value from being split into multiple words or expanded by globbing.

target='/srv/shared data'
cd -- "$target"

Backslashes and names that look like options

You can also escape spaces by putting a backslash in front of them.

cd Project\ Files

If a name starts with a hyphen, attach ./ or use the option end indicator -- to prevent it from being misunderstood as an option.

cd ./-archive
cd -- -archive

Using tab auto-completion allows the shell to properly escape spaces and special characters in paths, reducing typos.

Understanding PWD and OLDPWD

PWD representing the current location

Bash stores the new working directory in the PWD variable after a successful move. You can compare it with the pwd command to check the logical path remembered by the current shell.

printf '%s\n' "$PWD"
pwd

~+ is also replaced with the PWD value in Bash's tilde expansion.

printf '%s\n' ~+

OLDPWD representing the previous location

After a successful move, the previous working directory is stored in OLDPWD. cd - uses this value.

printf '%s\n' "$OLDPWD"
printf '%s\n' ~-

Immediately after starting the shell or before moving to a directory, OLDPWD may not exist.

Symbolic links and the -L, -P options

In paths that contain symbolic links, the logical path remembered by the shell may differ from the physical path resolved by the file system.

Preserve logical paths with -L

-L is the default behavior and processes .. based on the logical path components. If you moved through a symbolic link name, that name may also be retained in PWD.

cd -L /srv/current
pwd

It preserves the path structure entered by the user, making it easy to understand when working with project links or the current release link.

Follow physical paths with -P

-P interprets symbolic links as their physical target paths during navigation. It is used when you need to check the actual file system location or process .. based on the link target.

cd -P /srv/current
pwd -P

-e causes a failure status to be returned when used with -P if the current physical path cannot be determined after moving.

cd -P -e /srv/current

Searching frequently visited locations with CDPATH

CDPATH is a search path used when cd looks for a directory name that does not start with a slash. It is similar to PATH for finding executables but applies only to directory changes.

Example of setting CDPATH

CDPATH=.:~/projects:/srv/apps
export CDPATH
cd sample-app

It searches for sample-app in each location separated by colons. An empty entry or . represents the current directory. To prioritize a directory with the same name in the current location, placing . first is easy to understand.

Cautions when using CDPATH

When cd finds a directory in a non-empty CDPATH entry, it can display the absolute path moved to on the standard output. This is convenient in an interactive shell but can mix unexpected paths in script output.

In automation, use absolute paths or clear relative paths, and if necessary, remove the influence of search paths on the command with CDPATH=.

CDPATH= cd -- ./build

Execute the next command only if the change was successful

If cd fails but the next command continues to run, it can create or delete files in an unintended directory. It is safer to link the success status with a logical operator.

cd /srv/app && ./deploy.sh

In multi-line scripts, explicitly exit or handle errors on failure.

cd /srv/app || {
 printf '%s\n' 'Cannot move to the working directory.' >&2
 exit 1
}./deploy.sh

If you use a semicolon like cd path; command, the next command will execute regardless of whether the change succeeded.

Using cd in scripts and subshells

Why a script cannot change the parent's shell location

A normally executed shell script runs in a separate process, so cd inside the script only affects that process and its children. After the script ends, the working directory of the terminal that called it remains unchanged.

./change-directory.sh
pwd

To change the current shell's location, you can define a function or execute the script with source, but a sourced script can also change the current shell's variables and options, so you should verify that the content is trustworthy.

source ./change-directory.sh

A Subshell That Maintains Its Original Location After Operation

To work in a specific directory while keeping the location of the calling shell, you can create a subshell using parentheses.

(
  cd /srv/app && ./build.sh
)

Directory changes inside parentheses disappear when the subshell ends. To move and return in the current shell, you can also use pushd and popd instead of directly saving the existing path.

Why sudo cd Doesn’t Work

sudo cd /root generally cannot be used. cd is a built-in command of the current shell, and a process started by sudo cannot change the working directory of the parent shell.

If you need an administrator shell itself, you can start a new login shell according to the permission policy like this.

sudo -i

To run a single command with administrator privileges in a specific directory, either move in the current shell and apply sudo only to that command, or specify the working path and command in a separate shell.

cd /srv/app && sudo ./maintenance.sh
sudo sh -c 'cd /srv/app && ./maintenance.sh'

Use administrator privileges only where necessary and ensure that the paths and executables can be trusted.

Comparison of cd, pushd, and popd

Command Main use Features
cd Moves to the specified directory. You can return to the previous location using OLDPWD.
pushd Moves while saving the current location on the directory stack. Useful when moving between multiple locations, and Bash manages the stack.
popd Removes an item from the stack and moves to that location. Pairs with pushd to restore the saved location.
dirs Checks the current directory stack. You can display only the stack state without moving.

Frequently used move commands

Command Description
cd Move to the current user's home directory.
cd ~ Move to the home directory using tilde expansion.
cd .. Move to the parent directory.
cd ../.. Move to the directory two levels up.
cd - Return to the previous working directory.
cd / Move to the root directory of the file system.
cd ~/projects Move to the projects directory under the home directory.
cd -P path Moves following the physical path resolved from symbolic links.

Option summary

Option Description
-L Uses the logical path. This is the default behavior of Bash, allowing the symbolic link name to be maintained in the path.
-P Interprets symbolic links as the physical target path and moves there.
-e Used with -P, returns a failure status if it cannot determine the physical current path after moving.
-@ On supported systems, displays the extended attributes of files as if they were directories. This may not be supported in typical Linux environments.
-- Indicates the end of options and is used when treating directory names that start with a hyphen as arguments.

Common Errors

No such file or directory

The path may not exist, or you may have assumed the current location incorrectly. Check the base location with pwd and inspect the case sensitivity and spaces in the path.

pwd
ls -ld -- "target path"

Permission denied

You may not have execute permission on the target directory or any intermediate directories in the path. You need execute permission on each directory that makes up the path to move into a directory.

namei -l /path/to/directory

Before arbitrarily increasing permissions, verify whether the user needs to access this path and check the appropriate group or ACL policies.

Not a directory

The last component or intermediate components of the path might be regular files. Check their types with file and ls -ld.

file -- "target path"
ls -ld -- "target path"

FAQ

Is it normal that there is no output when executing the cd command?

Yes, it is normal. A successful cd to a normal path does not produce output. You can check your current location with pwd, and paths found using cd - or CDPATH may print the new path upon success.

How do I move up two levels to the parent directory?

cd.. /.. Use it. Each .. This parent directory represents a step and is connected by a slash.

Can I change the directory of the current terminal using a script?

A normally executed script cannot change the directories of the parent shell. To affect the current shell, you need shell functions or sources, but since you can also change other states of the current shell, use only trusted code.

Related articles and official documentation

More in This Category
Linux locate Command: Search Indexed File Paths Quickly

Linux locate Command: Search Indexed File Paths Quickly

Learn how Linux locate searches a filename database, how updatedb affects freshness, how to limit and filter matches, and when find is the better tool.

Linux date Command: Display and Format the Current Time

Linux date Command: Display and Format the Current Time

Learn how to display and Format the Current Time with the Linux date command, including practical examples, key options, and important precautions.

Linux head Command: Display the Beginning of a File

Linux head Command: Display the Beginning of a File

Learn how Linux head prints the first lines or bytes of files and pipelines, labels multiple inputs, excludes a trailing portion, and handles multibyte data.

Linux Tutorial / What Is Linux? Understanding the Kernel, Distributions, and Open Source

Linux Tutorial / What Is Linux? Understanding the Kernel, Distributions, and Open Source

Understand how the Linux kernel differs from a distribution, what user space and open source mean, and how to check your system's kernel and distribution versions.

Linux basename Command: Extract the Final Component of a Path

Linux basename Command: Extract the Final Component of a Path

Learn how to use the Linux basename command to remove directory prefixes and optional suffixes from path strings, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux cp Command: Copy Files and Directories

Linux cp Command: Copy Files and Directories

Learn how to copy files and directories with Linux cp, control overwrites, preserve attributes, handle symlinks, and verify important copies.

Linux reboot Command: Restart the System Safely

Linux reboot Command: Restart the System Safely

Learn how to restart the System Safely with the Linux reboot command, including practical examples, key options, and important precautions.

Linux diff Command: Compare Text Files and Directories

Linux diff Command: Compare Text Files and Directories

Learn how Linux diff compares text files and directories, produces unified patches, ignores selected whitespace changes, and reports differences through exit status.

Linux pkill Command: Signal Processes by Name

Linux pkill Command: Signal Processes by Name

Learn how to signal Processes by Name with the Linux pkill command, including practical examples, key options, and important precautions.

Linux uptime Command: Check Uptime and Load Averages

Linux uptime Command: Check Uptime and Load Averages

Learn how to use the Linux uptime command to check how long the system has been running and interpret load averages, with essential options, practical examples, output interpretation, and common troubleshooting tips.