Bash

Get Script's Own Directory

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
The "where am I" boilerplate that every nontrivial bash script needs. Resolves symlinks correctly with realpath, falls back gracefully if realpath is missing.
Bash
Raw
# Standard form — works for direct invocation and `bash script.sh`.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Symlink-resolving variant (use this if your script may be symlinked):
SCRIPT_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"

# Or with realpath (cleaner if you have GNU coreutils):
SCRIPT_DIR="$(dirname "$(realpath "${BASH_SOURCE[0]}")")"

echo "Script lives at: $SCRIPT_DIR"

# Source a sibling file relative to this script
source "$SCRIPT_DIR/lib/common.sh"
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.