2

这个有点难解释。考虑变量allfirstlastsome

a="apple mcintosh"
b="banana plantain"
c="coconut cashew"
all="$a $b $c"
first="$a"
last=$c"
some="$a $c"

这是我所拥有的:

echo "What do you want to install?"
echo "all, first, last, or some?"
read userinput

假设用户键入all,他的输入将被视为变量的名称:我希望下一个命令是pacman -S $all(等价于pacman -S apple mcintosh banana plantain coconut cashew)。同样,如果用户同时键入firstand last,则下一个命令必须是pacman -S $first $last(实际上应该执行pacman -S apple mcintosh coconut cashew)。

我曾经case/esac翻译userinput成一个变量,但我正在寻找一种更灵活和优雅的解决方案,因为这种方法不允许多个输入。

case $userinput in                                             
  all)   result="$all";;
  first) result="$first";;
  *)     exit;;
esac

pacman -S $result
4

2 回答 2

4

您所追求的是间接变量引用,其形式为${!var}

3.5.3 Shell参数扩展

[...]如果参数的第一个字符是感叹号(!),则引入了变量间接级别。Bash 使用由其余参数形成的变量的值作为变量的名称;然后扩展此变量,并将该值用于替换的其余部分,而不是参数本身的值。这称为间接扩展。

例如:

$ a="apple mcintosh"
$ b="banana plantain"
$ c="coconut cashew"
$ all="$a $b $c"
$ first="$a"
$ last="$c"
$ some="$a $c"
$ read userinput
all
$ result=${!userinput}
$ echo $result
apple mcintosh banana plantain coconut cashew

要扩展多个项目,请使用read -a将单词读入数组:

$ read -a userinput
first last
$ result=$(for x in ${userinput[@]}; do echo ${!x}; done)
$ echo $result
apple mcintosh coconut cashew
于 2013-08-01T16:39:20.107 回答
1

要从选项列表中读取用户输入,select您需要 bash。此外,当您开始询问“我如何动态构建变量名”时,请考虑使用关联数组:

a="apple mcintosh"
b="banana plantain"
c="coconut cashew"

declare -A choices
choices[all]="$a $b $c"
choices[first]="$a"
choices[last]="$c"
choices[some]="$a $c"

PS3="What do you want to install? "

select choice in "${!choices[@]}"; do
    if [[ -n $choice ]]; then
        break
    fi
done

echo "you chose: ${choices[$choice]}"

以上不处理多项选择。在这种情况下,然后(仍然使用上面的“选择”数组):

options=$(IFS=,; echo "${!choices[*]}")
read -rp "What do you want to install ($options)? " -a response
values=""
for word in "${response[@]}"; do
    if [[ -n ${choices[$word]} ]]; then
        values+="${choices[$word]} "
    fi
done
echo "you chose: $values"

这使用read's-a选项将响应读入数组。它看起来像什么:

$ bash select.sh 
What do you want to install (some,last,first,all)? first middle last
you chose: apple mcintosh coconut cashew 
于 2013-08-01T17:23:59.160 回答