Shell Scripting / Bash Tricks
Stop hardcoding those messy directory paths in scripts
đź§© The Challenge
You know that feeling when you move a project to a new server and every single relative path in your backup script suddenly explodes? I’ve spent way too many nights fixing hardcoded paths because I assumed the script would always run from the root.
đź’ˇ The Fix
Use a variable that resolves the script’s directory relative to its own location, no matter where you call it from. It makes your tools actually portable for once.
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
⚙️ Why It Works
By hitting readlink with the -f flag, you resolve all symlinks and get the actual path to the file, and then dirname just strips off the filename to leave you with the absolute directory path. It’s the only way to keep your scripts from breaking when you move them around or call them from a crontab.
🚀 Pro-Tip: Keep this line at the top of every script and you’ll never worry about your working directory again.
Linux Tips & Tricks | © ngelinux.com | 7/14/2026
