How can I just get the absolute path for the current script (multi-OS solution)?

I am looking for a simple solution to get the absolute path of the current script. It should 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 does not have the -f option.
  • "realpath $ 0" works on freebsd and linux, but not on macos: I don't have this command.

EDIT: Solution for retrieving the repository path script:

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

+3
source share
2 answers

For zsh, FWIW scripts:

#! /bin/zsh -
fullpath=$0:A
+1
#!/bin/sh

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

echo ${self}

" ". pwd -P POSIX, . readlink , POSIX.

, . - , realpath .

0

All Articles