0

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 ~]$
Sami Badra
  • 111
  • 2
  • 6
  • you didn't define FLAVOR_C_LOCATIONS, instead _B_ is repeated. Also "LOCATIONS" is not an array. – karakfa Mar 01 '18 at 04:05
  • Thanks for catching the variable name. So how would I define "LOCATIONS" as an array then? – Sami Badra Mar 01 '18 at 17:28
  • I'm not any other than `eval` will work. After constructing the location variable name `eval loc_values=\( \${${loc_var_name}[@]} \)` should work. – karakfa Mar 01 '18 at 17:42

0 Answers0