Skip to content

Instantly share code, notes, and snippets.

@jammycakes
Last active February 22, 2017 03:17
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 jammycakes/509f024f44b6a0f994c47e26e1602d21 to your computer and use it in GitHub Desktop.
Save jammycakes/509f024f44b6a0f994c47e26e1602d21 to your computer and use it in GitHub Desktop.
A snippet of code to detect the path to the current script. Works in bash and zsh.

This snippet detects various information about the shell script in which it is being executed. Copy and paste it into the top of your script.

Variables set are as follows:

  • $__SHELL: bash or zsh
  • $__SOURCED: true if the file was invoked using source filename or . filename, otherwise it will be blank.
  • $__SCRIPT_PATH: the full absolute path to the script.
  • $__SCRIPT_DIR: the full absolute path to the script's directory.
  • $__SCRIPT_PATH_DEREFERENCED: the full absolute path to the script, dereferencing all symbolic links.
  • $__SCRIPT_DIR_DEREFERENCED: the full absolute path to the script's directory, dereferencing all symbolic links.
function realpath () {
echo "$1" | python -c "import os.path, sys; print(os.path.abspath(sys.stdin.read().strip()))"
}
function dirname () {
echo "$1" | python -c "import os.path, sys; print(os.path.dirname(sys.stdin.read().strip()))"
}
function dereference () {
local link
link="$1"
while [ -L "$link" ]; do
link=$(echo "$link" | python -c "import os, sys; print(os.readlink(sys.stdin.read().strip()))")
done
echo $link
}
if [[ "${BASH_SOURCE[0]}" != "" ]]; then
# Bash
__SCRIPT_PATH="${BASH_SOURCE[0]}"
__SHELL="bash"
if [[ ${BASH_SOURCE[0]} != $0 ]]; then
__SOURCED=true
fi
elif [[ "$zsh_eval_context" != "" ]]; then
# zsh
__SCRIPT_PATH="$0"
__SHELL="zsh"
if [[ $zsh_eval_context =~ "file" ]]; then
__SOURCED=true
fi
fi
__SCRIPT_PATH=$(realpath "$__SCRIPT_PATH")
__SCRIPT_DIR=$(dirname "$__SCRIPT_PATH")
__SCRIPT_PATH_DEREFERENCED=$(dereference "$__SCRIPT_PATH")
__SCRIPT_DIR_DEREFERENCED=$(dereference "$__SCRIPT_DIR")
@demosdemon
Copy link

If you change those echo statements to printf %s "$1" then you can remove the calls to .strip() considering that they could erroneously remove legitimate whitespace.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment