2014-01-10 79 views
1

在shell程序中,我想在if語句中定義一個月變量,如下所示。但我似乎無法在if語句中定義一個變量 - 我一直在輸入一個錯誤消息,指出「command'dmonth'找不到。」任何幫助都感激不盡!Shell腳本:在if語句中定義一個變量

#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

我認爲你遇到與空格麻煩......這是在Bourne shell的顯著和它的dirivitives。 dmonth="Dec"是一項任務,dmonth = "Dec"是以'='和'Dec'作爲參數的命令。

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語句:

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