This article covers how to use the bash command cd.
If you want to change your directory in bash, you can use the cd command.
To show this in action, let's first cover quickly two commands we'll also be using:
- pwd will display the current directory to the console.
- mkdir will create a new directory.
Let's use pwd to see our current directory:
Now we can create two directories to move between:
mkdir firstFolder mkdir secondFolder
If we want to move from our current directory into the newly created firstFolder directory, we simply need to specify it after the cd command:
cd firstFolder pwd
Using pwd shows we have now moved into the firstFolder directory:
Switching to the parent directory
What if we want to move into the second directory we created, secondFolder? Let's use the same commmand again:
bash: cd: secondFolder: No such file or directory
Since the path supplied to cd is relative to the current directory, it is now looking for a secondFolder inside _firstFolder.
Instead, we need to move up to the parent directory first.
We can do so using the path ..:
# Go to the parent directory cd .. cd secondFolder pwd
Alternatively, you can use .. as part of the path:
cd ../secondFolder pwd
Go to the previous directory
In the examples above, we moved from Test/firstFolder to Test/secondFolder.
If we wanted to go back to firstFolder, we could use .. again.
We can also use -, which will move us back to the previous directory.
Switching to the home directory
There are two methods to switch to the home directory. The first, is to call cd with no arguments:
You can also use the path ~:
The benefit of the ~ path is we can use it as part of a longer path, to move to a directory relative to the home directory:
cd ~/Test pwd
Difference between .. and .
We've seen .., which refers to the parent directory.
The path . on the other hand, refers to the current directory:
cd . pwd