Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
See this question over on SO:… – Telemachus Jul 13 '09 at 21:21
And this one:… – Telemachus Jul 13 '09 at 21:23
Thanks for the hints! – Huxi Jul 13 '09 at 23:03
up vote 12 down vote accepted

I cheat and use perl for this very thing:

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.

share|improve this answer
This works, thanks a lot. I'll give you an upvote as soon as I can. Does anyone have a "pure shell" way of doing this? – Huxi Jul 13 '09 at 21:17
I'm afraid this is as good as it gets. (Given the many multiple-line "pure shell" hacks one can find on Google.) – Arjan Jul 13 '09 at 21:34
another possibility (though ugly) is to traverse the '..' path, memorizing (thru recursion or an array) until '..' returns the same file you just had (ie: you are at the top), then come back assembling the path as you go. I've seen Legato's Networker backup software doing this during strace as a method of obtaining a 'true' path (but perhaps not absolute). But it would be a lot more code than the above. – ericslaw Jul 14 '09 at 2:56
Not sure why someone modifed the code to use $1 instead of $0. Isn't $1 the first arg to the bash script? I wanted the path to the executing bash script, not it's first argument. – ericslaw Jul 3 '13 at 18:47
#!/usr/bin/env bash
scriptDir="$(cd "$(dirname "$0")" && pwd -P)"
share|improve this answer
I think you want dirname instead of basename – Adam Batkin May 20 '13 at 4:05
haha wish i found this an hour ago. Thanks! – Roy Rico Jul 15 '15 at 17:55
Works in MacOSX too. – Alexar Jan 14 at 12:10
This is super! There are many other over-complicated answers floating around. – Jason S May 28 at 9:21

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.