Shell脚本:在if语句中定义变量

时间:2014-01-10 18:09:03

标签: shell variables if-statement

在shell程序中,我想在if语句中定义一个月变量,如下所示。但是我似乎无法在if语句中定义一个变量 - 我不断发出一条错误消息,说“找不到命令'dmonth”。任何帮助都感激不尽!

    #Enter date:

    echo "Enter close-out date of MONTHLY data (in the form mmdd): "
    read usedate
    echo " "

    #Extract first two digits of "usedate" to get the month number:

    dmonthn=${usedate:0:2}
    echo "month number = ${dmonthn}"
    echo " "

    #Translate the numeric month identifier into first three letters of month:

    if [ "$dmonthn" == "01" ]; then
        dmonth = 'Jan'
    elif [ "$dmonthn" == "02" ]; then 
        dmonth = "Feb" 
    elif [ "$dmonthn" == "03" ]; then 
        dmonth = "Mar" 
    elif [ "$dmonthn" == "04" ]; then 
        dmonth = "Apr" 
    elif [ "$dmonthn" == "05" ]; then 
        dmonth = "May" 
    elif [ "$dmonthn" == "06" ]; then 
        dmonth = "Jun" 
    elif [ "$dmonthn" == "07" ]; then
        dmonth = "Jul" 
    elif [ "$dmonthn" == "08" ]; then 
        dmonth = "Aug" 
    elif [ "$dmonthn" == "09" ]; then 
        dmonth = "Sep" 
    elif [ "$dmonthn" == "10" ]; then 
        dmonth = "Oct"
    elif [ "$dmonthn" == "11" ]; then 
        dmonth = "Nov"
    else 
        dmonth = "Dec" 
    fi

    echo dmonth

2 个答案:

答案 0 :(得分:4)

我认为你在使用空白区时遇到了麻烦......它在Bourne shell及其衍生产品中具有重要意义。 dmonth="Dec"是一项任务,dmonth = "Dec"是一个以'='和'Dec'作为参数的命令。

答案 1 :(得分:1)

正如shellcheck告诉您的那样,您无法在作业中使用=周围的空格。

而不是dmonth = 'Jan',请使用dmonth='Jan'

为了使代码更漂亮,您可以使用数组并将其编入索引:

dmonthn=09
months=( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec )
dmonth=${months[$((10#$dmonthn-1))]}
echo "$dmonth"

或案例陈述:

case $dmonthn in
  01) dmonth='Jan' ;;
  02) dmonth='Feb' ;;
  03) dmonth='Mar' ;;
  ...
esac