pwd Command in Linux

pwd Command in Linux

The pwd command in Linux stands for print working directory and is used to display the full absolute path of the current directory you are working in.

It works by querying the system for your current location within the directory hierarchy and returns the path starting from the root (/).

Mastering pwd command in Linux is crucial for working effectively in the file system. By using various options and integrating pwd into scripts, you can enhance your efficiency and adapt the command to your needs.

Linux pwd Command Syntax:

By default, running pwd without any options prints the absolute path of the current working directory:

pwd [OPTION]

Prerequisites to Use pwd Command in Linux

Provide the options below to let this tutorial work correctly and move on.

  • A Linux VPS plan running one of the Linux distributions.
  • A non-root user with sudo privileges.
  • Access to Terminal/Command line.
  • Using a text editor such as Nano or Vim.

17 Practical Examples to Understand Linux pwd Command

The pwd Command in Linux is essential for users navigating the file system, especially when working across multiple directories, as it helps ensure they know their exact location within the file structure.

It’s frequently used in scripts and terminal sessions to verify the current working directory. Its versatility makes it an essential tool not only for basic navigation but also for debugging, scripting, and automation.

Let’s explore various ways you can use pwd through real-world examples.

1. Displaying the Current Directory Path

Running the pwd command in Linux without any options will output the full absolute path to your current working directory.

  • Syntax:
pwd
  • Example:
/home/username/projects

In this example, pwd outputs the absolute path of the directory you’re currently in. The path starts from the root `/` and goes down through the directories until the present location.

Note: An absolute path always starts with `/`, representing the root directory of the Linux file system.

2. Using pwd -P to Avoid Symlinks

The -P option tells pwd to print the physical location of the directory, ignoring any symbolic links you may have used to navigate.

  • Syntax:
pwd -P
  • Example:

Suppose you’ve created a symbolic link (symlink) pointing to /var/www/html but used that link to enter the directory. Running pwd -P will show:

/var/www/html

This ensures you’re getting the actual directory, not the symbolic link’s location.

3. Displaying Logical Path with pwd -L

The -L option ensures that pwd prints the logical directory path, which includes any symbolic links used during navigation.

  • Syntax:
pwd -L
  • Example:

If you’ve entered a directory via a symbolic link (symlink), running  pwd -L might return:

/home/user/symlink

This shows the path as entered, maintaining any symlinks.

4. Accessing the Current Directory via $PWD Variable

The $PWD environment variable automatically holds the path to the current directory. You can print this variable’s contents to see your current location.

Syntax:

echo $PWD
  • Example:
/home/username/documents

In this case, the command prints the directory path stored in $PWD, which is often the same output as running pwd.

5. Customizing Output with a Bash Script

You can integrate Linux pwd command into a script to enhance or personalize the output using echo command.

  • Script Example:
#!/bin/bash
p=$(pwd)
echo "You are currently in: $p"

Here’s how to create and run the script:

Create the script using a text editor:

vi directory.sh

Add the lines above to the script.

Save and make it executable:

chmod +x directory.sh

Run the script:

./directory.sh

The output will be personalized, such as:

You are currently in: /home/username/projects

6. Checking the pwd Command Version

There are two versions of the pwd command in Linux — a shell built-in and a binary version. You can check the version by running the following command:

  • Syntax:
/bin/pwd --version
  • Example:
pwd (GNU coreutils) 8.32

This command reveals the version of the binary pwd installed on your system.

7. Accessing the Previous Directory with $OLDPWD

The $OLDPWD variable holds the path to the previous directory you were in. You can print it using the echo command to check where you came from.

  • Syntax:
echo $OLDPWD
  • Example:
/home/username/downloads

This is useful if you want to trace back to the last directory you navigated from.

8. Viewing the pwd Help File

You can access the help file of Linux pwd command to understand all the available options and their uses.

  • Syntax:
pwd --help
  • Example Output:
Usage: pwd [OPTION]...
  -L    Use PWD from environment, even if it contains symlinks
  -P    Avoid symlinks when resolving the current directory

This output shows the list of options you can use with pwd.

9. Using pwd in a Bash Case Statement

You can incorporate pwd in more complex scripts to create interactive prompts. Here’s a script using a case statement:

  • Script Example:
#!/bin/bash
echo "Select an option:"
echo "1 - Show physical directory path"
echo "2 - Show directory with symlinks"
echo "3 - Show previous directory"
read choice
case $choice in
  1) echo "Physical directory: $(pwd -P)";;
  2) echo "Logical directory: $(pwd -L)";;
  3) echo "Previous directory: $OLDPWD";;
esac

After creating, saving, and executing the script, you can choose one of the options, and the corresponding path will be displayed.

10. Creating an Alias for pwd

You can simplify your workflow by creating an alias for pwd that automatically includes the -P option to avoid symbolic links.

Add this alias to your .bashrc file:

  • Syntax:
alias pwd='pwd -P'; echo "alias pwd='pwd -P'" >> ~/.bashrc

After adding this alias, every time you run pwdIt will display the physical location and ignore any symlinks.

11. Compare Logical and Physical Paths in One Command

You can combine both the -P and -L options in a single command to compare the physical and logical paths simultaneously.

echo "Logical path: $(pwd -L), Physical path: $(pwd -P)"

This command shows the logical path (which might include symlinks) and the physical path (which bypasses symlinks).

It helps identify any symbolic links involved in the current directory path.

12. Using pwd Inside a For Loop

You can use pwd in a for loop to display the working directory at different points in your script execution.

  • Example:
for dir in /etc /var /usr; do
  cd $dir
  echo "Now in directory: $(pwd)"
done

In this case, the pwd command prints the current working directory each time the loop changes to a new directory. This is helpful in scripts that traverse through multiple directories.

13. Combine pwd Command in Linux with Date Command

Sometimes it’s useful to log both the current directory and the time for tracking purposes in scripts or log files.

  • Example:
echo "Directory: $(pwd), Timestamp: $(date)"

This outputs both the absolute path of the current working directory and the exact time when the command was executed, which can be useful for logging script behavior.

14. Find Directory After Error Handling

When automating tasks, you might want to check the directory after handling errors. You can add pwd to confirm you are still in the correct directory after an error occurs.

  • Example:
cd /path/to/somewhere || echo "Failed to change directory, current location: $(pwd)"

If the cd command fails, pwd will display the current directory, ensuring you know where the script is still operating.

15. Store pwd Output for Later Use

You can store the output of the pwd command in a variable and use it later in your script, especially if you need to return to a previous directory.

  • Example:
current_dir=$(pwd)
# perform operations
cd /some/other/directory
echo "Back to original directory: $current_dir"
cd $current_dir

This script navigates to a different directory, performs some operations, and then returns to the original directory using the value stored in the $current_dir variable.

16. Detecting Directory Context in Shell Prompt

You can use pwd inside a custom shell prompt to display the current directory in your terminal prompt.

  • Example:
PS1='Current directory: $(pwd)$ '

This modifies your shell prompt to always display the current directory before each command you type, making it easier to keep track of your location in the filesystem.

17. Chain Commands with pwd

You can chain the pwd command with other commands to perform multiple actions in one line.

mkdir new_directory && cd new_directory && echo "Now in: $(pwd)"

This command creates a new directory, moves into it, and prints the current directory path using pwd all in one line. It ensures you’re aware of the location after each step.

What does the pwd command do in Linux?

The pwd (print working directory) command in Linux displays the full path of the current directory in the file system.

It’s used to check your location within the directory structure during a terminal session.

What is the Difference between pwd and $PWD in Linux?

The pwd command prints the current working directory, while $PWD is an environment variable that stores the current directory’s path.

While they often provide the same result, pwd can resolve physical or logical paths based on the options used (-P for physical and -L for logical paths), whereas $PWD simply reflects the current directory as stored by the shell.

This distinction is important, particularly in scripting, when handling symbolic links or needing exact directory information.

How to get the physical directory with pwd in Linux?

To get the actual physical directory, avoid symbolic links, and use the pwd -P option. This command outputs the real directory structure, resolving any symlinks.

For example:

pwd -P

This ensures you’re seeing the physical directory, not a symlink.

How to display symbolic links with pwd?

The -L option of the pwd command allows you to display the logical path, which includes any symbolic links, rather than the physical directory.

By default, pwd may already show the logical path, but using the -L option explicitly ensures this behavior. This is useful when you want to track your path through symlinks.

  • To use it:
pwd -L

This command will print the path with symbolic links, reflecting how you navigated to the directory, even if symlinks were used.

How to use pwd in shell scripting?

To use the pwd command in shell scripting, you can incorporate it to store and display the current working directory, which can help track locations during script execution.

For instance, you can assign the output of pwd to a variable and use it later in the script to return to the original directory after performing some operations.

Here’s an example:

#!/bin/bash
start_dir=$(pwd)  # Store the current directory
echo "Starting in: $start_dir"

# Perform some operations here, like changing directories
cd /some/other/directory

# Return to the original directory
cd "$start_dir"
echo "Back to: $(pwd)"

This approach ensures you always know your starting point and can return to it, which is especially useful in longer scripts that navigate through different directories.

Why does pwd show a different path after I follow a symlink?

When you change directories using a symbolic link, the pwd command might show the symlink path instead of the actual physical path.

This happens because pwd by default displays the logical path, which includes symbolic links.

To see the real, physical path (bypassing any symlinks), you can use the -P option:

pwd -P

This ensures the output shows the true directory structure. If you prefer to continue seeing the logical path, including symbolic links, you can use the default pwd or explicitly use the -L option:

pwd -L

How to use pwd in a script to track directories?

In shell scripts, the pwd command is often used to store the current directory for later use, especially when the script involves navigating to different directories.

This ensures that you can return to the original directory after performing operations elsewhere.

For example:

start_dir=$(pwd)  # Store the current directory
# Perform some operations, such as changing directories
cd /some/other/directory
# Return to the original directory
cd "$start_dir"

This technique is useful for maintaining context within scripts, particularly in complex directory structures, ensuring that the script returns to the starting point after completing its tasks.

Why does pwd in an SSH session show a different path than expected?

If you’re SSHing into a remote server and pwd shows an unexpected path, it may be due to the way symbolic links or user configurations are set up on the remote system.

Solution: Use pwd -P to get the real physical path, and check any .bashrc or login scripts that may alter the working directory when starting an SSH session

Conclusion

The pwd command is a simple but powerful utility in Linux, allowing users to find their current location in the file system.

Whether working in complex directory structures or dealing with symbolic links, pwd offers flexibility through its options like -L and -P, making it suitable for various use cases.

With the examples you reviewed, you can use different options to customize the command’s output, enhancing your control over how directory paths are displayed.

Additionally, integrating pwd into scripts can improve your efficiency, helping you track and manage working directories seamlessly.

Leave a Reply

Your email address will not be published. Required fields are marked.