How can I retrieve the absolute filename in a shell script on Mac OS X?

I'd like to retrieve the absolute file name of the script file that's currently executed. Links should be resolved, too.

On Linux, this seems to be done like this:

$(readlink -mn "$0")

but readlink seems to work very differently on Mac OS X.

I've read that this is done using

$(realpath $0)

in BSD but that doesn't work, either. Mac OS X does not have realpath.

Any idea?


Solution 1:

I cheat and use perl for this very thing:

#!/bin/bash
dirname=`perl -e 'use Cwd "abs_path";print abs_path(shift)' $0`
echo $dirname

You'd think I'd just write the entire script in perl, and often I do, but not always.

Solution 2:

#!/usr/bin/env bash
scriptDir="$(cd "$(dirname "$0")" && pwd -P)"

Solution 3:

Another approach:

# Install.
brew install coreutils

# Use the GNU variant.
grealpath --help