Absolute file path function for Bash shell scripts

19. juni 2012

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.


Counting occurrences of a word matching a regex

14. desember 2011

This is a brief code snippet showing how to use command line tools to count the occurences of words matching a regex. In the following example, I am trying to list all the unique hits on the urls from the apache access log matching «/chart». Les resten av dette innlegget »