Skip to content

Instantly share code, notes, and snippets.

@jammycakes
Last active Feb 22, 2017
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@demosdemon demosdemon commented Feb 22, 2017

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