How to get current working directory in Linux/Unix

The "pwd" command in Linux and Unix is used to display the current working directory.

Usage

In this tutorial, we will explain how to use the “pwd” command to get the current working directory in Linux and Unix, with examples.

Step 1: Open the terminal

The first step is to open the terminal on your Linux or Unix machine. You can do this by clicking on the terminal icon in the taskbar or by using the keyboard shortcut "Ctrl + Alt + T."

Step 2: Use the "pwd" command

Once the terminal is open, you can use the "pwd" command to display the current working directory. Simply type "pwd" and press enter.

user@host:~$ pwd
/home/user

Step 3: Use the verbose option

The "pwd" command also has a verbose option, "-P", which displays the physical directory, which could be different from the logical directory. This option is useful when working with symbolic links, it will show the real path instead of the symlink path. To use this option, you can type "pwd -P" and press enter.

user@host:~$ pwd -P
/home/user

The “pwd” command can also be used in combination with other command-line tools, such as "grep" and "awk", to filter and process the output. For example, you can use "grep" to search for a specific string within the output of the "pwd" command.

user@host:~$ pwd | grep "home"
/home/user

You can also use "awk" to format the output in a way that makes it easier to read or analyze.

Advertisements
user@host:~$ pwd | awk '{print $1}'
/home

Step 5: Use with shell scripts

You can also use the "pwd" command within shell scripts. For example, you can use the "pwd" command to save the current working directory to a variable for later use.

#!/bin/bash
current_dir=$(pwd)
echo "The current working directory is: $current_dir"

In conclusion, the "pwd" command is a simple yet useful command-line tool that can be used to display the current working directory in Linux and Unix. It has a verbose option that can be used to display the physical path of the directory. It can also be used in combination with other command-line tools to filter and process the output, and it can also be used within shell scripts. By following the steps above and examples provided, you will be able to get the current working directory on your Linux or Unix machine.

Advertisements

LEAVE A REPLY

Please enter your comment!
Please enter your name here