代码之家  ›  专栏  ›  技术社区  ›  codeforester

如何抑制日期输出中的前导零?

  •  1
  • codeforester  · 技术社区  · 7 年前

    我有以下代码:

    printf -v s '%(%S)T' -1 # grab the current second
    if ((s == 0)); then
      # at the top of the minute, run some code
    fi
    

    此代码在每分钟的第八秒和第九秒抛出错误:

    bash: ((: 08: value too great for base (error token is "08")
    bash: ((: 09: value too great for base (error token is "09")
    

    我如何纠正这一点?基本上,我们需要抑制 printf .

    1 回复  |  直到 7 年前
        1
  •  4
  •   codeforester    7 年前

    使用 - 格式字符串中的前缀,因此:

    printf -v s '%(%-S)T' -1
    

    这将抑制前导零。

    更通用的 way 解决这个问题的方法是这样在Bash算法中指定基,同时保持 printf 命令未更改:

    if ((10#$s == 0)); then
    

    Unix上的相关帖子;Linux堆栈交换: