I recently learned 1 a nice pattern to improve parameter handling in shell scripts. The pattern involves parameter expansion:
#!/usr/bin/env bash
set -euo pipefail
function main {
local arg1="${A1:?'FAIL. Provide A1 var'}"
echo $arg1
}
main
When calling the script (called t.sh
throughout this post), it will fail:
bash t.sh
# t.sh: line 7: A1: FAIL. Provide A1 var
But this will succeed:
It can also be used to provide default/required positional arguments.
#!/usr/bin/env bash
set -euo pipefail
function f1 {
local arg1="${1:?'FAIL. Provide as the first argument' }"
local arg2="${2:-default_two}"
echo "$arg1"
echo "$arg2"
}
function main {
f1 "foo" # <-- prints "foo" and "default_two"
f1 "foo" "bar" # <-- prints "foo" and "bar"