【问题标题】:obtaining epoch date from files in directory to define age for deletion从目录中的文件获取纪元日期以定义删除年龄
【发布时间】:2020-06-10 23:53:11
【问题描述】:

我正在尝试编写一个 bash 脚本来遍历目录中的文件,获取每个文件的纪元日期并将其与今天的纪元日期进行比较。如果文件超过 X 天,请将其删除。

我不断收到带有“+%s”选项的日期命令错误(使用 MacOS) 命令 > +%s> 直接在终端上运行时实际上可以工作,但是将其集成到 for 循环中会返回错误

错误是:./listfiles.sh: line 8: date -r DeleteThese/ACME.txt +%s : 表达式中的语法错误(错误标记是“DeleteThese/ACME.txt +%s”)

#!/bin/bash
tdyepoch=`date +%s`
thepath="DeleteThese/"
thefiles=$(ls -1 $thepath)
for i in $thefiles
do

        file_epoch=$(( date -r $thepath$i +%s ))
        ttl=$(( tdyepoch - file_epoch ))
        mins=$(( ttl / 60 ))
        hrs=$(( min / 60 ))
        dys=$(( hrs - 24 ))
        echo "$i, $file_epoch, $ttl, $mins, $hrs, $dys"
done

我在这里做错了什么......?我对 bash 并不陌生,但由于某种奇怪的原因,这个让我跺了跺脚。

谢谢!

【问题讨论】:

标签: bash macos date terminal


【解决方案1】:

$((...)) 进行算术扩展。您需要在您的 date 调用周围使用 $() 来代替命令替换。加上你shouldn't try to use the results of ls in a loop,而不是使用正常的文件名扩展。您还有其他一些问题,例如在脚本上运行 shellcheck 的变量名拼写错误也会提醒您。

清理完毕:

#!/bin/bash
tdyepoch=$(date +%s)
thepath="DeleteThese"
for file in ${thepath}/*
do
        file_epoch=$(date -r "$file" +%s)
        ttl=$(( tdyepoch - file_epoch ))
        mins=$(( ttl / 60 ))
        hrs=$(( mins / 60 ))
        dys=$(( hrs - 24 ))
        echo "$(basename "$file"), $file_epoch, $ttl, $mins, $hrs, $dys"
done

【讨论】:

  • 非常感谢... !!!这似乎是我所需要的......不完全确定为什么我被卡住了......不是我的第一个脚本,但它确实看起来像! ...我非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-08
  • 2012-04-17
  • 1970-01-01
  • 2023-03-05
  • 2018-10-31
  • 1970-01-01
相关资源
最近更新 更多