Articles

Finding the directory path of a bash script

In Unix on 05/03/2010 by pier0w Tagged: , ,

The full path of any bash script is stored in the argument variable $0 which also includes the name of the script it’s self. So the following script (find-path.sh):

#!/bin/bash
echo $0

Will produce the following output:

# /some/random/path/find-path.sh
/some/random/path/find-path.sh

It should be noted though that the $0 argument doesn’t actually record the scripts absolute path. It holds the path that that was used to reach the script. For example if the same script is run from a relative path the output will be different.

# cd /some/random
# path/find-path.sh
path/find-path.sh


# cd /some/directory
# ../random/path/find-path.sh
../random/path/find-path.sh

So to get the directory path of bash script you could write something to remove the last member of the string using the ‘/’ as a delimiter or you could just use the dirname program that reside on pretty much all Unix environments:

#!/bin/bash
echo `dirname $0`


# /some/random/path/find-path.sh
/some/random/path

Advertisements

Comments Off on Finding the directory path of a bash script

%d bloggers like this: