Linux offers the pre-installed “cd” command line tool to change the current working directory using the terminal. It allows the users to move into any given directory, parent directory, and root directory. In addition, the working of the “cd” command varies with the addition of different symbols such as cd-, cd~-, cd/, and cd .. to perform specific operations.
This post describes the main objective of “cd -” and “cd ~-” commands and their core difference.
What is “cd -” in Linux?
The “cd –” command prints the absolute path of the previously used directory and moves back to it. It jumps back directly to the previous directory, whether noticing the directory tree is very deep.
The following example shows the practical implementation of this concept.
Right now, the current directory of the terminal is “Home”, as shown below:
Run the “cd –” command, and it will jump back from “home” to the recently used directory tree i.e “/Sample/Extra/notes/tmp”:
$ cd -
The user is now in the “tmp” directory that follows the “/Sample/Extra/notes” directory structure.
What is “cd ~-” in Linux?
The addition of the “~(tild)” expansion with the “cd –” command only navigates to the previously working directory without printing its name absolute path. The working of the “cd ~-” command is just like a backspace key in computing machines.
The current working directory of the user, i.e., “itslinuxfoss” is “/Documents/notes/pics/imp/source” directory structure:
Execute the “cd ~-” command, and it will move to the previous working directory, i.e., “home” without echoing(printing) its absolute path in the terminal:
$ cd ~-
The output shows that the execution of the “cd ~-” command has been moved from “/Documents/notes/pics/imp/source” to the “home” directory.
Use “~-” to Print Old PWD
If the user wants to print the previous working directory name and its absolute path, then use the “~-” expansion with the “echo” command in this way:
$ echo ~-
The previously used directory has been displayed in the terminal.
Difference between “cd -” and “cd ~-” in Linux
The “cd” command with a simple “–(hyphen)” symbol i.e “cd –” prints the absolute path of the previous working directory and also navigates back into it.
On the other hand, the “cd ~-” command jumps to the previous working directory but can not print its absolute path in the terminal.
In Linux, the “cd –” command prints the recently used directory’s absolute path and jumps into it. However, the “cd ~-” command only jumps back into the last used directory and does not print that absolute path.
This guide has provided the basics, working, and usage of “cd -” and “cd ~-” commands along with their differences.