tags:

views:

34

answers:

2

I am trying to obtain the absolute path to the currently running script on OS X.

I saw many replies going for readlink -f $0. However since OS X's readlink is the same as BSD's, it just doesn't work (it works with GNU's version).

Any suggestions for an out of the box solution to this?

+1  A: 

There's a realpath() C function that'll do the job, but I'm not seeing anything available on the command-line. Here's a quick and dirty replacement:

#!/bin/bash

realpath() {
    [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}

realpath "$0"

This prints the path verbatim if it begins with a /. If not it must be a relative path, so it prepends $PWD to the front. The #./ part strips off ./ from the front of $1.

John Kugelman
I also noticed the C function but couldn't find any corresponding binary or anything. Anyway, your function just fits my needs nicely. Thanks!
Guillaume Bodi
A: 

Here's a C snippet that resolves symbolic links as well as Mac-type aliases:

http://my-sample-code.googlecode.com/svn/trunk/realpath/realpath.c

ernie