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:


#!/bin/bash
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 jon@hozbox.com ~ ]$ abspath mac_rsync/xCode/Projects/../Examples/ScrollViewSuite/ReadMe.txt 
/home/jon/mac_rsync/xCode/Examples/ScrollViewSuite/ReadMe.txt
[ 13:30 jon@hozbox.com ~ ]$ abspath repos/TestProj/
/home/jon/repos/TestProj/
[ 13:30 jon@hozbox.com ~ ]$ abspath xCode/Examples/ScrollViewSuite/ReadMe.txt2
Error: Could not find a file or directory at "xCode/Examples/ScrollViewSuite/ReadMe.txt2"!
[ 13:30 jon@hozbox.com ~ ]$ abspath ../../../../../../var/spool/mqueue/
/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

Comments

Leave a Reply