我正在尝试编写一个脚本并使其尽可能干净明亮。总之,我想呈现一个菜单,让一个人选择一个与他们喜欢的颜色相对应的数字。从那里我想获取菜单中带有数字的颜色名称,并将其用作将放置在其他地方的脚本中的变量。我的目标是在菜单后面有一个语法,但会使用颜色变量。这是让我回归的一件事。下面是一个片段..有什么想法吗?
color_pref=
while [ -z "$color_pref" ] ;
do
echo
echo
echo " ***************************************"
echo " What is your favorite color? "
echo " 1 - red"
echo " 2 - blue"
echo " 3 - green"
echo " 4 - orange"
echo " Select 1, 2, 3, or 4 :" \n
echo " ***************************************"
printf " Enter Selection> "; read color_pref
echo [[[whatever variable is for color selected]]]
答案 0 :(得分:1)
您可以使用case语句将set变量等于基于所选数字的颜色。
case $color_pref in
1) color=red ;;
2) color=blue ;;
3) color=green ;;
4) color=blue ;;
*) printf "Invalid color choice: %s" "$color_pref" >&2
exit;
esac
您可能需要查看select
命令,该命令负责处理大部分菜单显示和选择。
答案 1 :(得分:1)
您也可以使用关联数组:
declare -A colors=( [1]=red [2]=blue [3]=green [4]=orange )
示例:
declare -A colors=( [1]=red [2]=blue [3]=green [4]=orange )
color_pref=
while [ -z "$color_pref" ]
do
echo
echo
echo " ***************************************"
echo " What is your favorite color? "
echo " 1 - red"
echo " 2 - blue"
echo " 3 - green"
echo " 4 - orange"
echo " Select 1, 2, 3, or 4 :" \n
echo " ***************************************"
printf " Enter Selection> "; read color_pref
echo ${colors[$color_pref]}
done
或索引数组:
declare -a colors=('invalid' 'red' 'blue' 'green' 'orange' )
用法:
echo ${colors[$color_pref]}
答案 2 :(得分:0)
您可以将COLORS存储在类似
的数组中COLORS=('red' 'blue' 'green' 'orange')
然后您可以使用类似
的内容回显所选值echo $color_pref ${COLORS[color_pref-1]}
你需要添加一个
done
结束循环。总之类似的事情,
#!/usr/bin/env bash
COLORS=('red' 'blue' 'green' 'orange')
color_pref=
while [ -z "$color_pref" ] ;
do
echo
echo
echo " ***************************************"
echo " What is your favorite color? "
echo " 1 - red"
echo " 2 - blue"
echo " 3 - green"
echo " 4 - orange"
echo " Select 1, 2, 3, or 4 :" \n
echo " ***************************************"
printf " Enter Selection> "; read color_pref
echo $color_pref ${COLORS[color_pref-1]}
done