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).
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 )
You can determine the absolute path of any file in Windows by right-clicking a file and then clicking Properties. In the file properties first look at the "Location:" which is the path to the file.
To obtain the full path of a file, we use the readlink command. readlink prints the absolute path of a symbolic link, but as a side-effect, it also prints the absolute path for a relative path. In the case of the first command, readlink resolves the relative path of foo/ to the absolute path of /home/example/foo/.
In bash, there are a number of ways of retrieving the full address of a script. In particular, we can use realpath, readlink, or even create our custom little script. When we want to know the directory path, we can use the dirname command in our bash script to retrieve our directory path.
The pwd command displays the full, absolute path of the current, or working, directory.
#!/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.
For zsh scripts, FWIW:
#! /bin/zsh -
fullpath=$0:A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With