How To: get an absolute path from a relative path in bash

Thu. December 15, 2011
Categories: bash, Linux, Scripts, sh
Tags: , , , , ,

Here is a quick script I came up with while writing a larger shell script today. Feed it a relative file or directory path, and it will spit out its absolute path:

test -e "${1}" && ABSPATH=`cd \`dirname "${1}"\`; pwd`"/"`basename "${1}"`
test -n "${ABSPATH}" && echo ${ABSPATH} && exit 0

## Comment this next line to hide the error message when an invalid path is given as the argument
echo Error: Could not find a file or directory at \"${1}\"\!; exit 1

Here is how it works:

test -e "${1}" will test if the first argument exists. If it does exist, the && will keep the test going and ABSPATH=`cd \`dirname "${1}"\`; pwd`"/"`basename "${1}"` will be executed. This assigns a string to the ABSPATH variable that comprises the absolute dirname of the argument (by first cd‘ing into it and running the pwd command), a path separator (“/”) and the basename.

Make a file called abspath and place it in your ~/bin/ directory; here it is in action:

[ 13:30 ~ ]$ abspath mac_rsync/xCode/Projects/../Examples/ScrollViewSuite/ReadMe.txt 
[ 13:30 ~ ]$ abspath repos/TestProj/
[ 13:30 ~ ]$ abspath xCode/Examples/ScrollViewSuite/ReadMe.txt2
Error: Could not find a file or directory at "xCode/Examples/ScrollViewSuite/ReadMe.txt2"!
[ 13:30 ~ ]$ abspath ../../../../../../var/spool/mqueue/
Useful links if you want a better understanding of how this script works:

Bash Guide: Conditional statements
man dirname
man basename
man pwd


Leave a Reply