tags:

views:

95

answers:

3

Is there a sh equivalent of __FILE__, to give me the pathname of the currently executing file? POSIX solutions preferred, bash acceptable, thanks.

+1  A: 

Try using $0.

lhf
+1  A: 

Just a thought:

#!/usr/bin/env bash

# "$0" will expand to the name of the script, as called from the command line
readlink -f $0
The MYYN
That will be incorrect if the script is called via the $PATH variable.
sharth
Still (see edit)?
The MYYN
Note that `readlink` isn't entirely portable. OSX (and presumably BSD in general?) have a completely different version - where `-f` isn't supported. Rather, where `-f` means something different (and not helpful here).
Telemachus
`echo $(readlink -f $0)` works fine on OSX 10.6, just tested it.
The MYYN
Why are you using `echo`. Doesn't `readlink -f $0` by itself work?
Dennis Williamson
@Dennis Williamson: Yes sure, thanks, corrected.
The MYYN
@The MYYN You must have gnu's `coreutils` installed without the `g` prefixes. Here's what happens when I run that command: `readlink: illegal option -- f` (Yes, I'm on 10.6. I actually have gnu's `readlink` as well, but only under the alias `greadlink`. http://pastie.org/1057557 for an example.)
Telemachus