首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Shell脚本:在if语句中定义变量

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

Stack Overflow用户
提问于 2014-01-11 02:09:03
回答 2查看 9K关注 0票数 2

在shell程序中,我想在if语句中定义一个月变量,如下所示。但是我似乎不能在if语句中定义变量--我一直收到一条错误消息,说“没有找到命令'dmonth‘”。任何帮助都将不胜感激!

代码语言:javascript
复制
    #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
EN

回答 2

Stack Overflow用户

发布于 2014-01-11 02:21:34

我觉得你在使用空格时遇到了麻烦...它在Bourne shell中很重要,它是不同的。dmonth="Dec"是赋值,其中dmonth = "Dec"是以'=‘和'Dec’作为参数的命令。

票数 4
EN

Stack Overflow用户

发布于 2014-01-11 02:21:41

正如shellcheck会告诉你的那样,在赋值中不能在=周围使用空格。

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

为了使代码更美观,您可以使用一个数组并对其进行索引:

代码语言:javascript
复制
dmonthn=09
months=( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec )
dmonth=${months[$((10#$dmonthn-1))]}
echo "$dmonth"

或case语句:

代码语言:javascript
复制
case $dmonthn in
  01) dmonth='Jan' ;;
  02) dmonth='Feb' ;;
  03) dmonth='Mar' ;;
  ...
esac
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21051372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档