Two Bash helpers I keep reusing
Readable script output and stable relative paths without pulling in a logging framework.
I keep these two helpers in small Bash scripts. One makes output easy to scan. The other makes relative paths predictable.
loglog() {
local message="$1"
local level="${2:-info}"
case "$level" in
error)
echo "❌ $message"
exit 1
;;
success)
echo "✅ $message"
;;
warning)
echo "🔸 $message"
;;
info | *)
echo "🔹 $message"
;;
esac
}
run_from_script_dir() {
local script_dir
script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" || return
cd -- "$script_dir" || return
}
Output I can scan
loglog gives every script the same tiny output vocabulary. The default stays useful, so a normal message only needs its text:
loglog "Installing dependencies"
loglog "Configuration is missing" warning
loglog "Setup complete" success
An error is terminal by design. loglog "Could not continue" error prints the reason and exits with status 1, which keeps failure handling close to the message that explains it.
I like the emoji markers because they remain obvious in a noisy terminal without needing color support or a logging dependency.
Relative paths that stay relative to the script
A script normally inherits the caller's working directory. That makes a path such as ./config.json depend on where I launched the script.
run_from_script_dir resolves the directory of the current Bash source file through BASH_SOURCE[0], then moves the script into that directory. After that, local paths behave the same whether I start the script from its folder, another directory, or an absolute path.
The quoting matters. Script directories can contain spaces, and cd -- prevents a path beginning with - from being interpreted as an option. Keeping script_dir local also avoids leaking another variable into the rest of the script.
These helpers are intentionally for standalone Bash scripts. If the file is sourced into an interactive shell, cd changes that shell's directory and the error branch exits it. Inside normal setup scripts, that direct behavior is exactly why I like them.