Skip to content

Instantly share code, notes, and snippets.

@RogWilco
Last active September 17, 2020 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RogWilco/4262d89f2d98cda747df0287e4fd56b1 to your computer and use it in GitHub Desktop.
Save RogWilco/4262d89f2d98cda747df0287e4fd56b1 to your computer and use it in GitHub Desktop.
Get the absolute path of the current script, even when sourced from another script.
##
# Gets the present source directory (PSD) for the current script. Works when
# the script is executed directly or when it is being sourced from another
# script.
#
# @switch -P display the physical present source directory (all symbolic links resolved)
# @switch -L display the logical present source directory
#
# @stdout the absolute path to the script invoking the function
#
# @exit 0 on success
#
psd() {
local HERE="$( [ -z "${BASH_SOURCE[0]}" ] && echo "$0" || echo "${BASH_SOURCE[0]}" )"
local DIR="$( dirname $HERE )"
local PSD="$( cd "$DIR" && pwd $@ )"
# Compact version:
# ROOT="$( cd $( dirname "$( [ -z "${BASH_SOURCE[0]}" ] && echo "$0" || echo "${BASH_SOURCE[0]}" )" ) && pwd $@ )"
echo "$PSD"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment