【问题标题】:Shell - Subtracting an integer from a dateShell - 从日期中减去整数
【发布时间】:2016-12-01 19:11:48
【问题描述】:

我正在尝试从日期中减去一个整数。基本上我想说的是,如果是在本月 15 日之前,那么从该月中减去 1。因此,如果日期是 05-05-2016,我想使用 04 作为月份。

Month=`date +%m`
Day=`date +%d`

If [ $Day -lt 15 ]
    then
        Output_Month=$Month - 1
fi

这似乎不起作用,因为我假设它们采用两种不同的格式(日期和整数)。如何减去一个月或将月份转换为整数?

【问题讨论】:

  • 您可能会发现ShellCheck 很有用。它自动建议“使用 $((..)) 进行算术运算,例如 i=$((i - 2))”和“脚本区分大小写。使用 'if',而不是 'If'。”

标签: linux bash shell


【解决方案1】:

date 命令很聪明,你可以写:

if [ $Day -lt 15 ]; then
    Output_Month=$(date -d "-1 month" +%m)
fi

【讨论】:

    【解决方案2】:

    首先,你有错字:它是if(小写),而不是If。 要进行算术运算,您可以使用 $((..)) 构造。所以,可以写成:

    Month=`date +%-m`
    Day=`date +%d`
    
    if [ $Day -lt 15 ]
        then
            Output_Month=$((Month - 1))
    fi
    

    另外,请注意我在计算Month 时使用了-。这是因为 date +%d 打印时带有前导 0 并且任何带有前导的数字都是 八进制 数字。因此,当您将Month 设置为0809 时,这将是一个错误。 使用 - 会抑制前导 0

    【讨论】:

      【解决方案3】:

      Let 对算术运算符前后的空格有点挑剔。这应该可以帮助您获得答案:

      #!/bin/ksh
      
      Month=`date +%m`
      Day=`date +%d`
      
      if [ $Day -lt 15 ]
      then
         let Output_Month=$Month-1
         echo $Output_Month
      else
         let Output_Month=$Month+1
         echo $Output_Month
      fi
      

      我添加了用于测试的控制块,因为今天显然高于目标日期 15。现在是 27 号,所以要获得任何输出,我必须填充 else 子句。

      【讨论】:

        【解决方案4】:
        if [ "$Day" -lt "15" ] # No harm double quoting $Day, note this is integer comparison
            then
                (( Output_Month = Month - 1 )) #You may omit $ inside ((..)) construct
        fi
        

        【讨论】:

          猜你喜欢
          • 2023-04-06
          • 1970-01-01
          • 2013-01-03
          • 2012-10-07
          • 1970-01-01
          • 1970-01-01
          • 2013-02-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多