I'm trying to create a Bash function that assigns a default value to unset variables. This is a simplified example of my non-working script:
#! /usr/bin/env bash
# My broken validation function
validate_input() {
if [ -z "$1" ]; then
set -- "default"
fi
}
# Parse arguments
while [ "$#" -gt 0 ]; do
case "$1" in
--foo=*)
foo="${1#*=}"
;;
--bar=*)
bar="${1#*=}"
;;
*)
printf '%s\n' "Invalid argument ($1)"
exit 1
;;
esac
shift
done
# Validate foo and bar
validate_input "$foo"
validate_input "$bar"
# Print results
printf '%s\n' "foo: $foo"
printf '%s\n' "bar: $bar"
So, users can use the arguments --foo
and --bar
to set the variables $foo
and $bar
. The validate_input
function checks if a variable is set, and if not it's supposed to assign it the value "default". It's the last bit that isn't working:
$ ./test --foo=hello
foo: hello
bar:
The expected output is:
foo: hello
bar: default
I have read up on positional arguments and set
but I'm a bit out of my comfort zone here.
validate_input "foo"