Skip to content

Instantly share code, notes, and snippets.

@stubbetje
Last active August 29, 2015 14:13
Show Gist options
  • Save stubbetje/3244ddbf0cd0875cabc6 to your computer and use it in GitHub Desktop.
Save stubbetje/3244ddbf0cd0875cabc6 to your computer and use it in GitHub Desktop.
script_path -- portable `readlink -f`

(source: ValveSoftware/steam-for-linux#3671 (comment))

@TcM1911 Determining the path of the script being invoked, in a fully portable (w.r.t. platforms) and completely reliable manner, even in the face of symlinks, is a tricky problem and all too easy to get wrong. The only bullet proof way of doing it, of which I'm aware, is provided below (assumes bash); could be prepended to any script needing this functionality.

#!/bin/bash
script_path () {
local scr_path=""
local dir_path=""
local sym_path=""
# get (in a portable manner) the absolute path of the current script
scr_path=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && scr_path=$scr_path/$(basename -- "$0")
# if the path is a symlink resolve it recursively
while [ -h $scr_path ]; do
# 1) cd to directory of the symlink
# 2) cd to the directory of where the symlink points
# 3) get the pwd
# 4) append the basename
dir_path=$(dirname -- "$scr_path")
sym_path=$(readlink $scr_path)
scr_path=$(cd $dir_path && cd $(dirname -- "$sym_path") && pwd)/$(basename -- "$sym_path")
done
echo $scr_path
}
script_dir=$(dirname -- "$(script_path)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment