brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: BASH_SOURCE finds the folder a script lives in

Bash
~/tips/tip-shell-bash-source-script-dir

source "$script_dir/config.env"

Finds the directory of the running script so it can load files next to it.

A script that reads a config file next to it breaks the moment you start it from another folder. The usual fix is two lines at the top.

${BASH_SOURCE[0]} is the path of the file bash is currently running. Unlike $0 it still points at the script when the file is loaded with source, where $0 would be the name of the calling shell or script.

script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
source "$script_dir/config.env"

The cd ... && pwd part turns a possibly relative path into an absolute one. Quoting both substitutions keeps folders with spaces working, and the -- stops a folder name that starts with a dash from being read as an option.

After that you can refer to anything next to the script, no matter where you started it from:

cd /tmp
bash /mnt/user/appdata/<app>/scripts/backup.sh

Inside backup.sh, $script_dir is now /mnt/user/appdata/<app>/scripts, not /tmp. A relative config.env would have been looked up in /tmp.

Two catches. If the script is reached through a symlink, the result is the folder of the link, not of the real file. Resolve the path with readlink -f first when that matters. And BASH_SOURCE is bash only, so a script started with sh on a system where that is dash will not have it. The manual describes it as an array that goes with FUNCNAME, and index 0 is the right element for the top of a plain script.

Further reading: bash(1) manual page

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link