Linux / Unix Shell Script: Get The Current Directory

Linux / Unix Shell Script: Get The Current Directory

To get the current directory in a Linux or Unix shell script, you can use the pwd command.

The pwd command stands for "print working directory" and displays the current working directory of the shell.

To get the current directory in a shell script, you can use the pwd command in a command substitution:

current_dir=$(pwd)
Sour‮.www:ec‬lautturi.com

This will assign the output of the pwd command to the current_dir variable.

You can also use the $PWD shell variable to get the current directory. The $PWD variable is automatically set by the shell to the current working directory and does not require the pwd command.

For example:

current_dir=$PWD

Keep in mind that the pwd command and the $PWD variable only display the current working directory of the shell. If you change the working directory in the script or if the script is run from a different directory, the pwd command and the $PWD variable will return the new working directory.

To get the directory of the script itself, regardless of the current working directory, you can use the $0 variable, which contains the path of the script, and the dirname command to extract the directory:

script_dir=$(dirname "$0")

This will assign the directory of the script to the script_dir variable.

Keep in mind that these are just a few examples of how to get the current directory in a Linux or Unix shell script. You can customize the commands and variables to meet the specific requirements of your script. You should also regularly review and update the script to ensure that it is correct and efficient.

Created Time:2017-10-29 22:08:57  Author:lautturi