Skip to content

Instantly share code, notes, and snippets.

Last active Feb 22, 2017
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("
function dirname () {
echo "$1" | python -c "import os.path, sys; print(os.path.dirname("
function dereference () {
local link
while [ -L "$link" ]; do
link=$(echo "$link" | python -c "import os, sys; print(os.readlink(")
echo $link
if [[ "${BASH_SOURCE[0]}" != "" ]]; then
# Bash
if [[ ${BASH_SOURCE[0]} != $0 ]]; then
elif [[ "$zsh_eval_context" != "" ]]; then
# zsh
if [[ $zsh_eval_context =~ "file" ]]; then
__SCRIPT_PATH=$(realpath "$__SCRIPT_PATH")
__SCRIPT_DIR=$(dirname "$__SCRIPT_PATH")

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