There are multiple benefits of getting the current working directory path, such as a user can easily navigate to other directories. It helps users to specify file paths correctly and avoid errors when accessing or modifying files. Another great benefit is that users can verify they are in the correct directory before executing potentially harmful commands, such as deleting files or running scripts.
In this article, different commands will be discussed that can be used to get the current working directory path.
- Method 1: Using the pwd Command
- Method 2: Using the dirs Command
- Method 3: Using the readlink Command
Method 1: Using the pwd Command
The “pwd” or a print working directory is a built-in command used to display the path of that directory from where a user is currently accessing the terminal.
For example, if you are accessing the home directory in the terminal, then run the below command will show you its path as below:
The complete path of the home directory, in this case, is “/home/foss,” which can be seen after executing the pwd command.
If a user is accessing a different directory in a terminal, then it will also show the path of that directory. For example, if a user is in the Documents directory, then running this command will show them the path of that directory as shown below:
The complete path to access the “Documents” directory can be seen in the image below:
Method 2: Using the dirs Command
The dirs command is a shell built-in command in Linux used to display or manipulate the directory stack. This command is used to get the path of the current working directory by typing the below command.
When a user runs this command in the home directory, then a tilde (~) can be seen in the output which is equivalent to /home/foss.
The same thing can be seen if a user accesses the Documents directory, as shown below:
If a user wants to see the complete path just like the pwd command, then they can use the “-l” option along with the dirs command, as shown below:
$ dirs -l
The output shows the complete path /home/foss/Documents.
Method 3: Using the readlink Command
A user can also find the path of any working directory by using the “readlink” command. The “-f” option is used to show only the absolute path. The “/proc/self/cwd” is a symbolic link that will return the absolute path of the current working directory:
$ readlink -f /proc/self/cwd
The current working directory complete path can be seen in the output.
Finding the location of the current working directory is beneficial for navigation to other directories. Users can also ensure that they are executing the scripts or modifying the files from the correct path. Three commands can be used to get the current working directory which are pwd, dirs. and readlink.