Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simply retrieve the absolute path of the current script (multi OS solution)?

Tags:

shell

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 )

like image 684
Julien DAUPHANT Avatar asked May 02 '12 10:05

Julien DAUPHANT


People also ask

How do I find the absolute path of a file?

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.

How do I find absolute path in Linux?

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/.

How do I get the path of a bash script?

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.

How do I find absolute path in Ubuntu?

The pwd command displays the full, absolute path of the current, or working, directory.


2 Answers

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

like image 106
Michał Górny Avatar answered Sep 22 '22 17:09

Michał Górny


For zsh scripts, FWIW:

#! /bin/zsh -
fullpath=$0:A
like image 35
Stephane Chazelas Avatar answered Sep 23 '22 17:09

Stephane Chazelas