Unix – Portable Way to Get Script’s Absolute Path in zsh

filenamesportabilityshell-scriptsymlinkzsh

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:

mypath=$0:A

Now for other shells, though realpath() and readlink() are standard functions (the latter being a system call), realpath and readlink 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:

abs_path() {
  perl -MCwd -le '
    for (@ARGV) {
      if ($p = Cwd::abs_path $_) {
        print $p;
      } else {
        warn "abs_path: $_: $!\n";
        $ret = 1;
      }
    }
    exit $ret' "$@"
}

That would behave more like GNU's readlink -f than realpath() (GNU readlink -e) in that it will not complain if the file doesn't exist as long as its dirname does.

Related Question