get directory of shell script

How to Get Directory of Shell Script

Shell scripts allow you to automate tasks in Linux. Sometimes you may need to get directory of bash script or get folder where script is present. This can be useful in case you want to restrict shell script’s execution based on how it is called, or you want to customize shell script depending on its location. In this article, we will learn how to get directory shell script.


How to Get Directory of Shell Script

Here is a simple one line command to get folder of shell script. You need to add it to your shell script so that it displays the folder path.

#!/usr/bin/env bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

The above code will display the folder path of shell script, no matter where you call it from.

You may also use `dirname “$0″` or $(dirname “$0”) but its output will differ based on how the script is called.

Let us say you create an empty shell script.

$ sudo vi test.sh

Add the following lines to it.

#!/usr/bin/env bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
echo "Script location is $SCRIPT_DIR"

Save and close the file.

In the above code, BASH_SOURCE[0] contains the full file path of your shell script. dirname command is used to get the folder location containing the file. Once it is obtained, we use cd command to switch to this folder. The output of all these commands is discarded by sending it to dev/null. Finally we call pwd command to get our current working directory and store it to SCRIPT_DIR shell variable.

Make the script executable.

$ chmod +x test.sh

Run the code.

$ cd /home/ubuntu
$ ./test.sh
 Script location is /home/ubuntu

In this short article, we have learnt how to get folder location of shell script. You can use these commands in every shell, not just bash.

Also read:

How to Create Multiline String in Python
How to Disable SSH Password Authentication for Some Users
How to Kill Processes Running Longer Than Specific Time
How to Split Tar File into Multiple Files
How to Configure Samba Server in RHEL, CentOS

Leave a Reply

Your email address will not be published. Required fields are marked *