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

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


#!/bin/bash

CONF="../config/common.conf"

. $CONF

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.


#!/bin/bash

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

# Absolute path the script folder, thus /home/projects/sampleproject/scripts
SCRIPTPATH=$(dirname "$SCRIPT")

CONF="$SCRIPTPATH/../config/common.conf"

. $CONF

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

Leave a Comment

Back to top