I have a script that can be run with different "flavors". The logic for each flavor is almost identical (except for the values for variables it uses). So I decided to declare all variables for each flavor, using a namespace pattern (i.e. <flavorID>_<variable>
). I am trying to declare a generic variable at runtime based on the flavor used to run the script. In other words, I want to declare the variable <variable>
and make it equal to <flavorID>_<variable>
depending on the flavorID
from the CL argument. See the script below for clarification.
P.S. I realize I am only looping through one variable, but my actual real-world example has multiple arrays that I need to declare.
stack-example.sh:
#!/bin/bash
FLAVOR_OPT=${1} #This gets set via command line option
if ! [[ "$FLAVOR_OPT" =~ (A|B|C) ]]; then
echo "Usage: $0 { A | B | C }"
exit 1
fi
## Flavor A Variables ##
FLAVOR_A_NAME="Vanilla"
FLAVOR_A_COLOR="White"
FLAVOR_A_LOCATIONS=(
"Baskin-Robbins"
"Cold Stone"
"Dairy Queen"
)
## Flavor B Variables ##
FLAVOR_B_NAME="Chocolate"
FLAVOR_B_COLOR="Brown"
FLAVOR_B_LOCATIONS=(
"Cold Stone"
"Yogurtland"
"Yogurt Heaven"
"Yogurt Mill"
)
## Flavor C Variables ##
FLAVOR_C_NAME="Strawberry"
FLAVOR_C_COLOR="Red"
FLAVOR_C_LOCATIONS=(
"Baskin-Robbins"
"Dairy Queen"
"Yogurtland"
"Yogurt Mill"
)
for var in "NAME" "COLOR"; do
flavor_var=FLAVOR\_$FLAVOR_OPT\_$var
declare ${var}="${!flavor_var}"
done
############## This is where I am getting stuck ##############
##############################################################
for var in "LOCATIONS"; do
flavor_var=FLAVOR\_$FLAVOR_OPT\_$var[*]
tmp=("${!flavor_var}")
declare ${var}="${tmp[@]}"
done
echo "NAME = $NAME"
echo "COLOR = $COLOR"
echo "LOCATIONS (count) = $LOCATIONS (count = ${#LOCATIONS[@]})"
Sample Output using the script above:
[sbadra@stack ~]$ ./stack-example.sh A
NAME = Vanilla
COLOR = White
LOCATIONS (count) = Baskin-Robbins Cold Stone Dairy Queen (count = 1)
[sbadra@stack ~]$ ./stack-example.sh B
NAME = Chocolate
COLOR = Brown
LOCATIONS (count) = Baskin-Robbins Dairy Queen Yogurtland Yogurt Mill (count = 1)
[sbadra@stack ~]$ ./stack-example.sh C
NAME = Strawberry
COLOR = Red
LOCATIONS (count) = (count = 1)
[sbadra@rtev22-ansible-dev ~]$