Bash Script: Find Out In What Directory Script Is Stored Under Unix Or Linux

How can I find out the path of the directory in which my bash shell script is located and store that path in _base variable?

You need to use the combination of the following:

[a] readlink – Display value of a symbolic link or canonical file name. This is a safe way to get the target of a symbolic link.

[b] ${BASH_SOURCE[0]} or $0 – The name of the shell script file is stored in $0 or ${BASH_SOURCE[0]}

Please note that the following examples are only tested on the Bash shell running on Debian Linux. This code may not be portable and may break on other Linux distributions/Unix like operating systems.

Examples

Create a shell script as follows:

#!/bin/bash
# Name: /tmp/demo.bash : 
# Purpose: Tell in what directory $0 is stored in
# Warning: Not tested for portability 
# ------------------------------------------------
 
## who am i? ##
_script="$(readlink -f ${BASH_SOURCE[0]})"
 
## Delete last component from $_script ##
_base="$(dirname $_script)"
 
## Okay, print it ##
echo "Script name : $_script"
echo "Current working dir : $PWD"
echo "Script location path (dir) : $_base"

Save and close the file. Run it as follows:
$ chmod +x /tmp/demo.bash
$ /tmp/demo.bash

Sample outputs:

Script name : /tmp/demo.bash
Current working dir : /home/vivek
Script location path (dir) : /tmp

cd to /home/vivek
$ cd ~
$ /tmp/demo.bash

Sample outputs:

Script name : /tmp/demo.bash
Current working dir : /home/vivek
Script location path (dir) : /tmp

Run it as follows:
$ ../../tmp/demo.bash
Sample outputs:

Script name : /tmp/demo.bash
Current working dir : /home/vivek
Script location path (dir) : /tmp

Finally, create a symbolic link in /home/vivek and test it:
$ cd ~
$ ln -s /tmp/demo.bash
$ ./demo.bash
$ rm demo.bash

Sample outputs:

Script name : /tmp/demo.bash
Current working dir : /home/vivek
Script location path (dir) : /tmp

Know a better way to solve this problem? Add in the comments below.

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.