bash - 从目录中的文件获取纪元日期以定义删除年龄
问题描述
我正在尝试编写一个 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 并不陌生,但是由于某种奇怪的原因,这个让我跺了跺脚。
谢谢!
解决方案
$((...))
做算术扩展。您需要$()
在您的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
推荐阅读
- android - 您的回复url包含违禁词或违禁域:在Azure微软平台android平台配置时
- spring - org.springframework.http.InvalidMediaTypeException:无效的 MIME 类型“XML;charset=ISO-8859-1”:不包含“/”
- python - 在 django rest 框架中更改用户名
- fiware - FIWARE Orion,NGSIv2 订阅具有结构化值的属性
- yocto - 如何将 /dev/root 文件系统大小设置为分区大小
- robotframework - 如何使用机器人框架在 SAP GUIShell 上双击元素?
- sql - 在 SQL 中的同一查询中引用不同的 id
- android - 如何将viewModel注入Fragment?
- c# - 使用 Linq Select 创建一个包含比原始列表更多项目的列表
- linux - 如何在没有 libstdc++ 依赖的情况下使用 b2 构建 C 程序?