【问题标题】:Value too great for base (error token is "2021_08_25")基础值太大(错误标记为“2021_08_25”)
【发布时间】:2021-11-03 15:30:26
【问题描述】:

我在一个目录中有以下文件:

2021_08_26.txt

2021_09_2.txt

2021_08_25.txt

2021_08_27.txt

其中我想根据文件名删除超过 8 天的文件。为此任务编写了以下脚本。

#!/bin/bash

f8days=$(date +%F --date="-8 days")
for file in 20*
do
    if [[ $file -gt $f8days ]]
    then
        rm -rf "$file"
    fi
done

但是在运行我的脚本时,我遇到了下面提到的错误:

./old-log-delete.sh: line 6: [[: 2021_08_25: value too great for base (error token is "2021_08_25")
./old-log-delete.sh: line 6: [[: 2021_08_26: value too great for base (error token is "2021_08_26")
./old-log-delete.sh: line 6: [[: 2021_08_27: value too great for base (error token is "2021_08_27")
./old-log-delete.sh: line 6: [[: 2021_09_2: value too great for base (error token is "2021_09_2")

这个错误的原因和可能的解决方案是什么?

【问题讨论】:

  • -gt 只比较整数,不比较字符串。使用>

标签: linux bash scripting


【解决方案1】:

我最初将问题作为Comparing two strings containing '_' lexicographically in bash 的副本关闭,但由于您专门尝试测试文件是否早于给定日期,我想我可能会推荐以下内容:

touch -t $(date +%Y%m%d%H%M.%S --date="-8 days") boundary
for file in 20*; do
    if [[ $file -ot boundary ]]; then
        rm -rf -- "$file"
    fi
done

这会创建一个修改日期为过去 8 天的空文件,然后检查 $file 是否比该空文件旧。


虽然 bash 允许您按字典顺序将字符串与 > 进行比较,但比较取决于区域设置,而 -ot 则不是。

【讨论】:

    【解决方案2】:

    -gt-lt-eq 运算符保留用于整数值。 2021_08_25 不是整数值。它包含不被接受的_ char。

    字符串使用><=操作符。

    您可以根据需要删除_,如下示例:

    strdate="2021_08_25"
    intdate=${strdate//_/}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多