在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发布于 2014-01-11 02:21:34
我觉得你在使用空格时遇到了麻烦...它在Bourne shell中很重要,它是不同的。dmonth="Dec"是赋值,其中dmonth = "Dec"是以'=‘和'Dec’作为参数的命令。
发布于 2014-01-11 02:21:41
正如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' ;;
...
esachttps://stackoverflow.com/questions/21051372
复制相似问题