Skip to content

Instantly share code, notes, and snippets.

@mrclay
Last active May 2, 2022 23:58
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 mrclay/f0648650b6f987232411c4b4103bceef to your computer and use it in GitHub Desktop.
Save mrclay/f0648650b6f987232411c4b4103bceef to your computer and use it in GitHub Desktop.
Shell: Getting directory of code or active script
#!/bin/bash
# Execution-relative (all shells). Get dir path of the script executed
# by the user.
__0="$(CDPATH= cd -- $(dirname -- $0) && pwd -P)"
echo "$__0"/bar
# Code-relative (bash/zsh only). Get dir path of *this file*,
# independent of which script was executed by the user.
__FILE="$([ -n "$BASH_SOURCE" ] && echo "$BASH_SOURCE" || echo "${(%):-%x}")"
__DIR="$(CDPATH= cd -- $(dirname -- $__FILE) && pwd -P)"
# E.g. Path of a subdirectory
echo "$__DIR"/bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment