Skip to content

Instantly share code, notes, and snippets.

@panos--
Last active January 10, 2022 08:55
Show Gist options
  • Save panos--/593616 to your computer and use it in GitHub Desktop.
Save panos--/593616 to your computer and use it in GitHub Desktop.
Bourne Shell script path detection
ME="$0"
REAL_ME="$ME"
while [ -h "$REAL_ME" ]; do
LINK_TARGET="$(readlink "$REAL_ME")"
case "$LINK_TARGET" in
/*) ;;
*) LINK_TARGET="$(dirname "$REAL_ME")/$LINK_TARGET"
esac
REAL_ME="$LINK_TARGET"
done
BINDIR="$(dirname "$REAL_ME")"
case "$BINDIR" in
/*) ;;
*)
cd "$BINDIR"
BINDIR="$PWD"
cd - >/dev/null
;;
esac
@panos--
Copy link
Author

panos-- commented Sep 23, 2010

Detects the parent directory of the executed shell script. Handles invocations through absolute (/bin/foo) and relative (../qux/foo) path specifications, invocations from $PATH (foo). Also resolves intermediate symlinks (absolute and relative).

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