How to Find the Directory Where a Bash Script Is Located from within the Script
While bash scripting you may require the location of the script to automate various tasks. There are two types of paths in Linux:
- Relatives Path: Relative is the current working directory.
- Absolute Path: This is the complete path of the directory and files.
One of the most common ways to determine the location of a bash script is to use the pwd command. The pwd command (print working directory) will show the current directory.
So, in many situations simply using pwd command does not work as it gives only the path of the currently working directory.
For example, if the script is in the Downloads directory and being executed from the Desktop then the output will contain the /home/usr/Desktop not the location of the bash script file that is /home/usr/Downloads.
This tutorial is about getting the path of the directory in which bash script file is located from within the script.
How to Get Directory Path Where Bash Script File Is Located
Another way to determine the directory of a Bash script is to use the dirname command. The dirname command takes a file path as an argument and returns the directory portion of the path.
To use dirname command to determine the directory of a script, you would call the command with the path till the last non-slash components to the script as the argument.
For more details about dirname execute the following commands in the terminal:
Only dirname will not work, we need another command that is readlink. The readlink command print resolved the symbolic link. Get more information about this command by running:
Now, create a script:
And type:
echo "The bash script path is $(dirname -- "$(readlink -f – "$0")";)";
To run the script use:
Let’s change the directory and see what is the output:
Note: In one case the above script will not work if the file is sourced instead of executing as it can be seen in the following output:
The output is /home/sam/Desktop whereas the script file is present in the /home/sam directory.
Conclusion
In conclusion, there are multiple ways to determine the directory of a bash script from within the script itself. The dirname along with readlink utility can be used to determine the directory of a script. However, simply using pwd command does not work as it gives only the currently working directory.