简体   繁体   中英

Case Statement in a while loop, shell scripting

I'm writing up a brief shell script which takes in a number from 1 to 12 and prints out the corresponding month. January = 1 February = 2 etc...

This is what I wrote so far and it's working fine:

#!/bin/sh 
x=0 
echo Enter the number 
read x 
case $x in 

1) 
echo January
;; 
2) 
echo February
;; 
3) 
echo March
;; 
4) 
echo April
;; 
5) 
echo May
;; 
6) 
echo June
;; 
7) 
echo July
;;
8) 
echo August
;;
9) 
echo September
;; 
10) 
echo October
;; 
11) 
echo November
;; 
12) 
echo December
;; 
*) 
echo Not sure that about one 
;; 

esac

However, I was wondering if it's possible to put a case statement into a while loop? so that when someone chooses the number they can choose another one after that again and again. so the program stops only when the user types in "exit", for example.

Is it possible? or is there a better option than using the while loop?

Thank you!

Of course:

while true; do
    read x
    case $x of
        exit) break ;;
        1) echo January ;;
        2) echo February ;;
        # ...
        12) echo December ;;
        *) echo "Unknown response, enter a number 1-12 or type 'exit' to quit" ;;
    esac
done

Using a bash select statement is a good choice here:

months=( January February ... December )
select choice in "${months[@]}" Exit; do
    if [[ $choice = "Exit" ]]; then
        break 
    elif [[ " ${months[*]} " == *" $choice "* ]]; then
        echo "$choice"
    else
        echo "invalid selection: $REPLY"
    fi
done

You can also do something like this

PS3="month or <q> to exit: ";
select m in $(cal -y | awk '(NR-2)%9 == 0 {print}'); do [[ "$REPLY" == 'q' ]] && break; echo "m=$m"; done

in case you don't want to type the months.

Which works in different languages depending on the value of the LANG env variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM