Pinpoint Your Script’s Real Home, No More Guessing
Shell Scripting / Bash Tricks
Pinpoint Your Script’s Real Home, No More Guessing
🧩 The Challenge
Ever written a script, tested it locally, then dropped it on a server as a symlink or put it in /usr/local/bin, and suddenly all its relative paths broke? You thought `dirname “$0″` would save you, but it just pointed to the symlink’s parent, not where your config files *actually* lived. It’s a royal pain to debug, and I’ve wasted far too much time tracking down why my `../config/app.conf` wasn’t found.
💡 The Fix
There’s a short combination of commands that’ll always give you the absolute path to your script’s true location, even if it’s been symlinked halfway across the filesystem or called from a different working directory. It ensures your script always knows exactly where its companions are.
SCRIPT_PATH=$(readlink -f "${BASH_SOURCE[0]}")
SCRIPT_DIR=$(dirname "$SCRIPT_PATH")
⚙️ Why It Works
This two-liner really gets to the bottom of it. `BASH_SOURCE[0]` gives us the path to the script itself, even if it’s a symlink. `readlink -f` then does the heavy lifting, resolving that symlink to its absolute, canonical path. Finally, `dirname` just pulls out the directory portion, giving you the true, physical location of your script, no matter how it was called.
🚀 Pro-Tip: Stick this `SCRIPT_DIR` variable at the top of every script. No more `../` guesswork, just solid, predictable paths.
Linux Tips & Tricks | © ngelinux.com | 10/21/2026
