Mar 12, 2009

Find the full path of your bash script

Usually people use the following way to get the fullpath of bash script (for the sake of various reasons, like locate the base dir etc):
export mypath=$dirname{"$0"}

However you can't get absolute path with this method, it get the relative path of $0

Someone use this code to probe the path:
export mypath=$dirname{$PWD}

This is unfortunately does NOT reach your goal: to get the full path of the script location. It turns out the full path of your current dir when you invoke the script.

A tested solution is provided by someone's posts to this thread:

# bash - find path to script
abspath=$(cd ${0%/*} && echo $PWD/${0##*/})

# to get the path only - not the script name - add
path_only=`dirname "$abspath"`

#display the paths to prove it works
echo $abspath
echo $path_only

Another interesting article about this topic can be found at google code


Greenland said...

This method breaks when invoke the script by "source". In the latest bash, a fix could be:

change the ${0%/*} from
abspath=$(cd ${0%/*} && echo $PWD/${0##*/})
to ${BASH_SOURCE[0]%/*}

Greenland said...

There is still a problem with the above comment. Once we invoke "source xx", you will get a cd error. Here is a complete solution:

if [[ ! $ME =~ "\/" ]];then
mypath=$(cd ${0%/*} && echo $PWD/${0##*/})
mypath=`dirname ${mypath}`

Thomas Fritz said...

You could also try this:

regis_desgroppes said...

echo `dirname $0 | xargs readlink -e`

Alexandr Chertkov said...

Using dirname with readlink might be more explicit:

About Me

My photo