how do i create a shell script with multiple choic

2019-06-05 06:03发布

问题:

Here is what I am trying to do

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...

My guess is i need a combination of case and if statements but i am unable to wrap my head around the problem.

回答1:

Use the select statement as @Barmar suggested.

Based on your example:

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..."

I used a|b|c) to group multiple options, but you could provide separate code paths for each one. *) can be used as an "else" clause. Use break to break out of the menu loop. Use ;; between clauses in the case statement and ; between statements in a single clause.