cd
Description
The cd command, also known as chdir(change directory), is a command-line shell command used to change the current working directory in various operating systems. It can be used in shell scripts and batch files.
The syntax for the command is:
cd [directory]
Use cases
Imagine you have a folder (
videogames) on your computer where you keep all your video games. You use thecdcommand to go there so you can play your favorite games.cd videogamesSuppose you have a folder (
music) where you store your music. You usecdto enter that folder to listen to your favorite songs.cd musicImagine you are working in a project folder named
my_projectthat is located within aprojectsdirectory, which, in turn, is inside yourDocumentsdirectory. To move up to the parent directory (i.e.Documents), you can use thecd ..command.cd ..You're working in two directories:
sourceanddestination. You want to quickly switch back and forth between them. You can usecd -to toggle between these directories.cd source cd - # Switches to "destination" cd - # Switches back to "source"
Additional Section
Navigating to the
rootDirectoryTo navigate to the
rootdirectory, which is the top-level directory in the file system, we can usecd /command.cd /Navigating to
homeDirectoryTo navigate to
homefolder, where personal files and settings are stored, we can use thecdcommand with either username or the tilde (~) symbol.cd susheelOR
cd ~OR
cdNavigating Directory with spaces in them
Suppose you have a directory named `My Documents`` with a space in the name, and you want to navigate to it. To do this, you need to enclose the directory name in quotes.
cd "My Documents"Note: You can also use escape character to achieve same result
cd My\ DocumentsNavigating using absolute paths and relative paths
Absolute Path
- An absolute path specifies the complete directory structure from the root directory to the target directory.
- It always begins with a forward slash (
/) in the Unix-like systems.
Example
Suppose you have the following directory structure:
/ ├── home │ └── user │ ├── documents │ └── pictures └── var └── logsTo navigate to the
picturesdirectory using an absolute paths:cd /home/user/picturesRelative Paths
- A relative path specifies the location of the target directory relative to your current working directory.
- It doesn't start with a forward slash.
Example
If you are currently in the
documentsdirectory./ ├── home │ └── user │ ├── documents │ └── pictures └── var └── logsTo navigate to the
picturesdirectory using a relative pathcd ../pictures
Note: You can learn more about absolute and relative path from here.
Exercises
You are in the
videogamesdirectory and want to navigate to themoviesdirectory, which is a sibling ofvideogames. How would you use the cd command to achieve this?Directory Tree
. ├── movies └── videogamesYou want to quickly switch between two directories named
workandprojectsmultiple times. How would you use the cd command to achieve this?