Bash script absolute path with OS X

bash, macos, path

Solution

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`.

Problem

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). Is there an out-of-the-box solution to this?

Original source

Related problems