The cd
command in Linux stands for “change directory”. It is used to navigate between directories in the filesystem. By specifying a directory path as an argument, you can move into that directory. If no argument is provided, cd
takes you to your home directory. The command is essential for navigating the filesystem, whether you’re working in the terminal or writing scripts.
It supports absolute paths (starting from the root /
), relative paths (starting from the current directory), and special shortcuts like ~
for the home directory and ..
to move up one level. With cd
, you can efficiently move around the filesystem and access the files and directories you need.
Navigate to a Directory
cd /path/to/directory
Example:
cd /var/www/html # Move to the web root directory
Go to Home Directory
cd ~ # Using tilde
cd # Without arguments (also goes to home)
Move Up One Directory
cd ..
Example:
From /home/user/docs
, moves to /home/user
.
Move Up Multiple Directories
cd ../../ # Go up two levels
Example:
From /home/user/docs/project
, moves to /home/user
.
Return to Previous Directory
cd -
Switches between the current and previous directory.
Example:
From /etc
, run cd /var/log
, then cd -
returns to /etc
.
Navigate to Root Directory
cd /
Takes you to the root of the filesystem.
Use Environment Variables
cd $HOME # Same as cd ~
cd $OLDPWD # Go back to the last directory (like cd -)
Handle Spaces in Directory Names
cd "My Documents" # With quotes
cd My\ Documents # With backslash
Escapes spaces to navigate into folders like My Documents
.
Use Wildcards
cd Dir* # Navigate to the first directory matching "Dir*"
Example:
If Dir1
and Dir2
exist, cd Dir*
moves to Dir1
.
Resolve Symlinks Physically
cd -P symlink_dir
Forces cd
to resolve the physical path (ignores symbolic links).
Combine with Command Substitution
cd $(dirname $(which nginx)) # Go to the directory of the nginx binary
Changes to the directory where a command (e.g., nginx
) is located.
Navigate to Directories with Special Characters
cd "dir#name" # Quotes handle special characters
cd dir\#name # Backslash escapes the special character
Use Absolute vs. Relative Paths
cd /etc/nginx # Absolute path
cd ../../usr/local/bin # Relative path
Script-Friendly Directory Changes
cd /target/dir && ./run_script.sh # Navigate and run a script
Changes directory only if the command succeeds.
Handle Directories Starting with -
cd -- -dirname # Use "--" to stop option parsing
Example:
Navigate to a directory named -test
:
cd -- -test
Bonus: Shortcut Aliases
Add aliases to your ~/.bashrc
for frequent directories:
alias cddot='cd ~/projects/dotfiles' # Quick access to dotfiles
alias cdlog='cd /var/log' # Jump to logs
Then run cddot
or cdlog
to navigate instantly.
Key Notes
- Use
Tab
to auto-complete directory names. cd .
stays in the current directory (rarely useful, but valid).- Combine
cd
withls
to explore directories:
cd /var/log && ls -l