Find the Absolute Path / Directory of a Bash Script

Recently, while writing a script I needed to know what directory the script resides in from within the script. A few google searches later I found a couple solutions. Jotting them down here for fellow googlers. 🙂

Solution 1:

ABSPATH="$(cd "${0%/*}" 2>/dev/null; echo "$PWD"/"${0##*/}")"
DIRPATH=`dirname "$ABSPATH"`

Solution 2:

LSOF=$(lsof -p $$ | grep -E "/"$(basename $0)"$")
ABSPATH=$(echo $LSOF | sed -r s/'^([^\/]+)\/'/'\/'/1 2>/dev/null)

I ended up using Solution 1, because its not dependent on any external command.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.