5

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 )

Community
  • 1
  • 1
Julien DAUPHANT
  • 240
  • 1
  • 10
  • 1
    FYI, `realpath` is available on Debian and Ubuntu in the `realpath` package. – Fred Foo May 02 '12 at 12:32
  • What is "the absolute path"? If /tmp/foo and /tmp/bar are (hard) links to the same file, which one is the absolute path? – William Pursell May 02 '12 at 13:29
  • 1
    What are you trying to achieve? And AFAIK there is no portable way to get symlink destination for a file, only the directory as you have already found. Also, that should be `pwd -P` there. – Michał Górny Aug 27 '12 at 15:56
  • Note that the solution you added to your question, `DIR="$( cd "$( dirname "$0" )" && pwd )"` does _not_ tell you where your script file truly lives if it was invoked via a _symlink_ - it only tells you where the _symlink_ lives (and using `pwd -P` would then resolve to the symlink directory's true path, but that is not the same). – mklement0 Sep 16 '19 at 16:44
  • Closely related (asks for the script's _directory_ path): https://stackoverflow.com/questions/29832037/how-to-get-script-directory-in-posix-sh – mklement0 Sep 16 '19 at 16:59

2 Answers2

4
#!/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.

mklement0
  • 245,023
  • 45
  • 419
  • 492
Michał Górny
  • 16,912
  • 2
  • 46
  • 75
1

For zsh scripts, FWIW:

#! /bin/zsh -
fullpath=$0:A
Stephane Chazelas
  • 5,014
  • 2
  • 27
  • 29