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

时间:2017-11-20 19:06:53

标签: linux bash shell

我正在编写一个简短的shell脚本,它从1到12中输入一个数字并打印出相应的月份。 1月= 2月1日= 2等...

这是我到目前为止写的,它工作正常:

#!/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

但是,我想知道是否可以将case语句放入while循环中?所以当有人选择号码时,他们可以一次又一次地选择另一个号码。因此,只有当用户键入“exit”时,程序才会停止,例如。

有可能吗?还是有比使用while循环更好的选择?

谢谢!

3 个答案:

答案 0 :(得分:1)

当然:

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

答案 1 :(得分:1)

在这里使用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

答案 2 :(得分:0)

您也可以这样做

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

如果您不想输入月份。

根据LANG env变量的值,它使用不同的语言。