Shell script – how to find out the directory in which it resides?

My shell script resided in the directory /home/projects/sampleproject/scripts and in the shell script I included a configuration file relatively as below:




When I executed shell script from the script folder it ran successfully but when I executed it from the home folder /home/projects/ it gave error “config file not found”. One solution was to┬áhard code the absolute path but I did not want to do it. The solution which I preferred was to the find the absolute script directory path in the script first and then define configuration file path relative to it.

Here is the code that I used to get the script directory path inside the script and include the configuration file.


# Absolute path to the script, e.g. /home/projects/sampleproject/scripts/
SCRIPT=$(readlink -f "$0")

# Absolute path the script folder, thus /home/projects/sampleproject/scripts



Now the script runs without error from home folder as well as script folder.

Leave a Comment

Back to top