Re: obtaining the absolute path of a shell script within itself
"Martin F. Krafft" <madduck@madduck.net> writes:
> how can i obtain the absolute path of the script within itself,
>
> echo `pwd`/$0,
>
> returns a POSIX-valid path like
> /home/madduck/edu/swat/../../bin/myscript
>
> but this method only works for relative paths. if i call myscript as
> /home/madduck/bin/myscript then this method yields
>
> /home/madduck/edu/swat//home/madduck/bin/myscript
>
> which is a different path (and most likely invalid).
>
> i *could* check the first character for a '/' and act accordingly, but
> there's got to be an easier way...
I'm not sure what you mean by easier (shorter, i assume), but that is
certainly not a bad way, as it can be implemented entirely using shell
builtins:
case $0 in
/*) abspath=$0 ;;
*) abspath=$PWD/$0 ;;
esac
echo $abspath
Off hand, I can think of only one alternative, which is quite elegant
and also normalises the pathname (removing .. and .):
abspath=$(cd ${0%/*} && echo $PWD/${0##*/})
(i.e. cd to the directory component of $0 and append the basename of
$0 to the PWD)
Interestingly, Plan9 contains a command which does exactly what you
want; see <URL:http://www.cs.bell-labs.com/magic/man2html/1/cleanname>
--
Leonard Stiles <ljs@uk2.net>
Reply to: