使用bash脚本并使用case语句

时间:2014-04-01 16:11:21

标签: linux bash shell ubuntu fedora

我尝试创建一个bash命令,在该命令中输入1到12之间的数字,它使用switch命令但在bash shell中使用case命令。我只需要确保我有正确的想法,或者如果我完成了

#!/bin/bash
1="January"
2="February"
3="March"
4="April"
5="May"
6="June"
7="July"
8="August"
9="September"
10="October"
11="November"
12="December"
case "1" in
print "$1"
case "2" in
print "$2" 
case "3" in
print "$3"
case "4" in
print "$4"
case "5" in
print "$5"
case "6" in
print "$6"
case "7" in
print "$7"
case "8" in
print "$8"
case "9" in
print "$9"
case "10" in
print "$10"
case "11" in
print "$11"
case "12" in 
print "$12"
echo "Please enter a number 1 through 12"
read input_variable
echo "$input_variable"

2 个答案:

答案 0 :(得分:3)

我害怕说你有点不对劲。这里有点像它的东西:

#!/bin/bash

echo "Please enter a number 1 through 12"
read input_variable

case $input_variable in
    1) 
        echo "January"
        ;;
    2) 
        echo "February"
        ;;
    3) 
        echo "March"
        ;;
    4) 
        echo "April"
        ;;
  # 5), 6) etc.
    *) # anything else
        echo "not recognised" 
        ;;
esac

@Charles Duffy是对的,你实际上并不需要case。你可以使用这样的数组:

编辑:在我写这篇文章时,我看到了@devnull的改进!

#!/bin/bash

echo "Please enter a number 1 through 12"
read input

months=( January February March April May June July August September October November December )

[ $input -gt 0 -a $input -le 12 ] && echo "${months[input-1]}"

或者如果您愿意,可以在数组的开头使用虚拟条目(感谢@chepner)

months=( "" January February March April May June July August September October November December )

[ ! -z "${months[input]}" ] && echo "${months[input]}"

答案 1 :(得分:0)

使用:

read -p "Enter a number between 1 and 12: " input

因为它简化了代码。然后使用:

case $input in 
汤姆·费内奇(Tom Fenech)表示

但是,案例陈述更多的是针对相同类型的结果进行测试,而是根据结果的结果对其执行不同的操作。你在这里回应所有东西,所以是的,将字符串存储在一个数组中,然后根据输入输出它。