简体   繁体   English

while循环中的Case语句,shell脚本

[英]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. 我正在编写一个简短的shell脚本,该脚本接受一个从1到12的数字,并打印出相应的月份。 January = 1 February = 2 etc... 一月= 2月1日= 2等...

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? 但是,我想知道是否可以将case语句放入while循环中? 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. 因此,例如,仅当用户键入“ exit”时,程序才会停止。

Is it possible? 可能吗? or is there a better option than using the while loop? 还是有比使用while循环更好的选择?

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: 在这里使用bash select语句是一个不错的选择:

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. 根据LANG env变量的值,它可以以不同的语言工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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