What is a portable way for a (zsh) script to determine its absolute path?
On Linux I use something like
mypath=$(readlink -f $0)
…but this is not portable. (E.g., readlink
on darwin does not recognize the -f
flag, nor has any equivalent.) (Also, using readlink
for this is, admittedly, a pretty obscure-looking hack.)
What's a more portable way?
Best Answer
With
zsh
, it's just:Now for other shells, though
realpath()
andreadlink()
are standard functions (the latter being a system call),realpath
andreadlink
are not standard command, though some systems have one or the other or both with various behaviour and feature set.As often, for portability, you may want to resort to
perl
:That would behave more like GNU's
readlink -f
thanrealpath()
(GNUreadlink -e
) in that it will not complain if the file doesn't exist as long as its dirname does.