2014-01-10 2 views
1

В командной оболочке я хотел бы определить переменную месяца в if-statement, как показано ниже. Но я не могу определить переменную в if-statement - я продолжаю получать сообщение об ошибке, которое говорит «command» dmonth «not found». Любая помощь будет высоко ценится!Shell script: Определить переменную в if-statement

#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

Я думаю, что у вас проблемы с пробелами ... это важно в оболочке Борна, и это дирижирует. 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 $dmonthn in 
    01) dmonth='Jan' ;; 
    02) dmonth='Feb' ;; 
    03) dmonth='Mar' ;; 
    ... 
esac