2

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!

0

3 Answers 3

8

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.