Absolute file path function for Bash shell scripts

An often wanted function when writing shell scripts is one that when given a file or directory, returns the absolute file path of the file. Googling for this will return many results, but few that are cross platform compatible. For instance will a search often bring up use of readlink, but this is not useful on BSD systems (such as Mac) and will thus only (?) work on Linux.

One solution that was both elegant, uncomplicated and works on all bash systems, was found on LinuxQuestions. This will probably only work in Bourne style shells, but is easy to read and reuse:

function abspath {
	if [[ -d "$1" ]]
	then
		pushd "$1" >/dev/null
		pwd
		popd >/dev/null
	elif [[ -e $1 ]]
	then
		pushd $(dirname $1) >/dev/null
		echo $(pwd)/$(basename $1)
		popd >/dev/null
	else
		echo $1 does not exist! >&2
		return 127
	fi
}

I have included it in my shell function library on GitHub.

Legg igjen en kommentar