What is $PWD in Linux?

The “$PWD” is an environment variable of the built-in Linux “pwd” command short form of “Present Working Directory.” It contains the absolute path of the current working directory starting from the “root” directory that is represented by “\(forward-slash).” It is quite useful when the users want to get the path of the current directory where they are working. 

This today’s post will illustrate the objective, working, and usage of the “$pwd” in Linux.

  • How Does the “$PWD” Work?
  • How to Use “$PWD” in Linux?
    • Use “$PWD” in the Terminal
    • Use “$PWD” in the Script
    • Use “$OLDPWD” for Old Working Directory

How Does the “$PWD” Work?

The “$PWD” environment variable shows the complete/absolute path of the current working directory. The generalized syntax of “$PWD” is written below:

$PWD

The “$” sign represents that the “PWD” is not a command; it is an environment variable:

The output shows the absolute path of the current directory and tells that it is a directory.

The directories shown in the path are separated by forward-slash(\). The first “\” forward slash denotes the root directory, and the last shows the current working directory.

How to Use “$PWD” in Linux?

The “$PWD” environment variable can be utilized in the scripts or the terminal to check the current working directory. This section carries out the use of “$PWD” with the help of different examples.

Example 1: Use “$PWD” in the Terminal

The “$PWD” can be used with “echo” to get the path of the current directory as below: 

$ echo $PWD

The “$PWD” shows the complete path of the current working directory.

Alternative:

The “$PWD” provides the same output as the “pwd” command line tool:

$ pwd

Example 2: Use the “$PWD” in the Script

An existing “code.sh” script is opened in the “nano” editor:

$ nano code.sh

Script Content:

#!/bin/sh

var="$PWD"
echo "The current working directory is $var"

In the “code.sh” script:

  • The “var” variable assigns a value of “$PWD” environment variable.
  • The “echo” statement displays the specified double quotes statement alongside the “$var” value.

Execute the script in the terminal:

$ ./code.sh

The output prints the value of “$PWD,” i.e., the current working directory is “home/itslinuxfoss.”

Example 3: Use “$OLDPWD” For Old Working Directory

The “$OLDPWD” is another extended “$PWD” environment variable that displays the previous/old working directory:

$ echo $OLDPWD

The previous working directory is “/home/itslinuxfoss/Documents.”

Conclusion

The “$PWD” is an environment variable that stores the complete path of the current directory. This task can be used in the bash script as the command substitution or in the terminal as an environment variable.

This post has explained the objective, working, and usage of the “$PWD” environment variable in Linux.