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 (

echo $0

Will produce the following output:

# /some/random/path/

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/

# cd /some/directory
# ../random/path/

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:

echo `dirname $0`

# /some/random/path/


Comments Off on Finding the directory path of a bash script

%d bloggers like this: