How can I simply retrieve the absolute path of the

2020-07-14 04:18发布

I am looking for a simple solution to retrieve the absolute path of the current script. It needs to be platform independent (I want it to work on linux, freebsd, macos and without bash).

  • "readlink -f $0" works on linux but not on freebsd and macos: readlink doesn't have the "-f" option.
  • "realpath $0" works on freebsd and linux but not on macos: I don't have this command.

EDIT : Solution for retrieve the path of the repository of the script :

DIR="$( cd "$( dirname "$0" )" && pwd )" (source : Getting the source directory of a Bash script from within )

标签: shell
2条回答
手持菜刀,她持情操
2楼-- · 2020-07-14 04:44
#!/bin/sh

self=$(
    self=${0}
    while [ -L "${self}" ]
    do
        cd "${self%/*}"
        self=$(readlink "${self}")
    done
    cd "${self%/*}"
    echo "$(pwd -P)/${self##*/}"
)

echo "${self}"

It's «mostly portable». Pattern substitution and pwd -P is POSIX, and the latter is usually a shell built-in. readlink is pretty common but it's not in POSIX.

And I don't think there is a simpler mostly-portable way. If you really need something like that, I'd suggest you rather try to get realpath installed on all your systems.

查看更多
做自己的国王
3楼-- · 2020-07-14 04:50

For zsh scripts, FWIW:

#! /bin/zsh -
fullpath=$0:A
查看更多
登录 后发表回答