Shell脚本:在if语句中定义变量
在shell程序中,我想在if语句中定义一个月变量,如下所示。但我似乎无法在if语句中定义变量——我一直收到一条错误消息,上面写着“command'dmonth'not found.”任何帮助都将不胜感激Shell脚本:在if语句中定义变量,shell,variables,if-statement,Shell,Variables,If Statement,在shell程序中,我想在if语句中定义一个月变量,如下所示。但我似乎无法在if语句中定义变量——我一直收到一条错误消息,上面写着“command'dmonth'not found.”任何帮助都将不胜感激 #Enter date: echo "Enter close-out date of MONTHLY data (in the form mmdd): " read usedate echo " " #Extract first two digits
#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
我想你在空白处遇到了麻烦。。。这在伯恩壳牌公司和它的董事会中意义重大
dmonth=“Dec”
是一个赋值,其中dmonth=“Dec”
是一个以“=”和“Dec”为参数的命令。正如您所知道的,在赋值中不能在=
周围使用空格
使用dmmonth='Jan'
代替dmmonth='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