1. Introduction

Quite a few times, we want to derive the path of the bash script, which we run on the command line. We usually need that path to help us to access files relative to the real location of the bash script in the filesystem.

In this tutorial, we shall learn the inner workings of achieving the same, whenever the bash script is a symbolic link.

The shell command readlink resolves the given file to its absolute path, after resolving the symbolic links. An example usage of readlink is:

$ls -ltar rlink 
lrwxrwxrwx 1 naresh naresh 14 Dec 13 11:28 rlink -> ../readlink.sh
$readlink -f rlink
/home/naresh/blogs/readlink.sh

As we can see above, we have a symbolic link to a file. Using the command readlink with -f  option, we can easily determine the absolute path of the file

Whenever we invoke a bash script, the $0 variable captures the script name. This variable identifies either the relative path of the script or the absolute path of the script. The path can also be a symbolic link to the actual script. The sample script:

#!/usr/bin/env bash
SCRIPTDIR=$(dirname "$(readlink -f "$0")")
echo "absolute path of the script $0 is $SCRIPTDIR"

As shown above, we are using three ideas from the bash script to determine the script directory

  • $0 is the bash variable that captures the script name
  • readlink command resolves the script name to its absolute path
  • dirname command extracts the directory from the absolute path

The variable SCRIPTDIR stores the directory of the bash script.

3. realpath

The shell command realpath is another handy command which can be used to find the absolute path of any file, given its relative path or a symbolic link to the file. An example of usage is:

$ls -ltar rpath
lrwxrwxrwx 1 naresh naresh 14 Dec 11 20:17 rpath -> ../realpath.sh
$realpath rpath
/home/naresh/blogs/realpath.sh

As illustrated above, using the command realpath, we can easily determine the absolute path of the file. We can also use realpath bash command along with the BASH_SOURCE environment variable to get the script location. The sample script:

#!/usr/bin/env bash
MYDIR=$(dirname "$(realpath  "$BASH_SOURCE")")
echo "absolute path of the script ${BASH_SOURCE} is $MYDIR"

As illustrated above, we are using two new ideas from the bash script to get the result

  • $BASH_SOURCE is the bash variable that captures the script name
  • realpath command resolves the script name to its absolute path

The variable MYDIR stores the directory of the bash script.

4. Conclusion

In this article, we saw two ways of determining the absolute path of a bash script, irrespective of how it is invoked.

Comments are closed on this article!