首页 > 解决方案 > 从目录中的文件获取纪元日期以定义删除年龄

问题描述

我正在尝试编写一个 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 并不陌生,但是由于某种奇怪的原因,这个让我跺了跺脚。

谢谢!

标签: bashmacosdateterminal

解决方案


$((...))做算术扩展。您需要$()在您的date呼叫周围进行命令替换。另外,您不应尝试在循环中使用 ls 的结果,而应使用正常的文件名扩展。您还有一些其他问题,例如在脚本上运行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

推荐阅读