I've looked over a couple other variable variable posts here but still seem stuck with what I'm trying to attempt.
I have an existing script that has a series of similar block like
set_name="something"
# Required values
var1=$(REQUIRED_ENV_VAR=/path/to/somewhere mybinary -p "key1_${set_name}")
if [[ -z "$var1" ]]; then
echo "Cannot find required var1"
exit 1
fi
var2=$(REQUIRED_ENV_VAR=/path/to/somewhere mybinary -p "key2_${set_name}")
if [[ -z "$var2" ]]; then
echo "Cannot find required var2"
exit 1
fi
# Optional, okay to be empty
var3=$(REQUIRED_ENV_VAR=/path/to/somewhere mybinary -p "key3_${set_name}")
var4=$(REQUIRED_ENV_VAR=/path/to/somewhere mybinary -p "key4_${set_name}")
I was trying to factor some of the boilerplate checks out to keep this set of lookups assignment easier to read (in my opinion anyway). The last iteration I had attempted (clearly not working) looks like
ZTest () {
var=$1
if [[ -z "${!var}" ]]; then
echo $2
exit 1
fi
}
VarRequire () {
var=$1
key=$2
errmsg=$3
VarLookup ${!var} $key
ZTest ${!var} $errmsg
}
VarLookup () {
var=$1
key=$2
${!var}=$(REQUIRED_ENV_VAR=/path/to/somewhere mybinary -p "$key")
}
# Required
VarRequire "var1" "key1_${set_name}" "Cannot find required var1"
VarRequire "var2" "key2_${set_name}" "Cannot find required var2"
# optional
VarLookup "var3" "key3_${set_name}"
VarLookup "var4" "key4_${set_name}"
The end result is I would be able to reference $var1, $var2, $var3, $var4 down the line in the script just the same as the original.
Is what I'm attempting possible in bash?
localqualifier to limit the scope of function variables.