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:

#!/bin/bash
#==========================
# 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

4 comments:

Unknown 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]%/*}

Unknown 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:

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

Anonymous said...

You could also try this:
http://fritzthomas.com/open-source/linux/384-how-to-get-the-absolute-path-within-the-running-bash-script/

regis_desgroppes said...

alternative:
echo `dirname $0 | xargs readlink -e`