Shell Scripting / Bash Tricks
Stop guessing where your scripts are actually running from
đź§© The Challenge
Scripts often break the second you move them into a crontab or symlink them somewhere else because relative paths stop pointing to where you think they are. I’ve spent way too many nights debugging why a script couldn’t find its own config file just because I launched it from a different directory.
đź’ˇ The Fix
Use a standard idiom to get the absolute directory of your script so your paths are always anchored to the script’s location, not the user’s current directory. It makes your code portable and saves you from hardcoding absolute paths that change between dev and production.
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
⚙️ Why It Works
By grabbing the directory of the file currently being sourced and jumping into it before calling pwd, you lock down the working directory regardless of where you triggered the script from. It’s a clean way to ensure your file lookups are relative to the script itself.
🚀 Pro-Tip: Always wrap that command in quotes and define it near the top of your script so every subsequent operation can just reference $SCRIPT_DIR/config.conf instead of guessing.
Linux Tips & Tricks | © ngelinux.com | 9/7/2026
