如何使用多选菜单变量创建shell脚本?

时间:2015-02-07 01:42:20

标签: bash shell if-statement

这是我想要做的事情

Please pick from the following  
1) area1  
2) area2  
3) area3

Now pick a place based on the area you chose  
1) place1  
2) place2  
3) place3

Based on $area and $place here is what you need...

我的猜测是我需要case和if语句的组合,但我无法解决问题。

1 个答案:

答案 0 :(得分:2)

使用select语句作为@Barmar建议。

根据您的示例:

echo 'Please pick from the following'

select area in area1 area2 area3
do
        case $area in 
        area1|area2|area3)   
                break
                ;;
        *)
                echo "Invalid area" 
                ;;
        esac
done

echo 'Now pick a place based on the area you chose'
select place in place1 place2 place3
do
        case $place in
        place1|place2|place3)
                break
                ;;
        *)
                echo "Invalid place"
                ;;
        esac
done

echo "Based on $area and $place here is what you need..."

我使用a|b|c)对多个选项进行分组,但您可以为每个选项提供单独的代码路径。 *)可以用作“else”子句。使用break打破菜单循环。在;;语句中使用case,在单个子句中的语句之间使用;