0

我有一个可以以不同“口味”运行的脚本。每种风味的逻辑几乎相同(除了它使用的变量的值)。所以我决定使用命名空间模式(即<flavorID>_<variable>)为每种风格声明所有变量。我试图根据用于运行脚本的风格在运行时声明一个通用变量。换句话说,我想根据CL 参数声明变量<variable>并使其等于。有关说明,请参阅下面的脚本。<flavorID>_<variable>flavorID

PS 我意识到我只循环一个变量,但我实际的真实示例有多个我需要声明的数组。


堆栈示例.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[@]})"


使用上述脚本的示例输出

[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 ~]$
4

0 回答 0