我需要为 Web 服务器编写一个脚本,该脚本将清除超过 14 天的文件/文件夹,但保留最后 7 个文件/目录。到目前为止,我一直在做我的研究,这是我想出的(我知道语法和命令不正确,但只是为了让你明白):
ls -ldt /data/deployments/product/website.com/*/ | tail -n +8 | xargs find /data/deployments/product/website.com/ -type f -type d -mtime +14 -exec rm -R {} \;
这是我关于脚本应该如何运行的思考过程(我更像是一个 Windows 批处理专家):
列出目录内容
If contents is less than or equal to 7, goto END
If contents is > 7 goto CLEAN
:CLEAN
ls -ldt /data/deployments/product/website.com/*/
keep last 7 entries (tail -n +8)
output of that "tail" -> find -type f -type d (both files and directories) -mtime +14 (not older than 14 days) -exec rm -R (delete)
我看过很多使用 xargs 和 sed 的示例,但我就是不知道如何将它们放在一起。
最佳答案
#!/bin/bash
find you_dir -mindepth 1 -maxdepth 1 -printf "%T@ %p\n" | \
sort -nrk1,1 |sed '1,7d' | cut -d' ' -f2 | \
xargs -n1 -I fname \
find fname -maxdepth 0 -mtime +14 -exec echo rm -rf {} \;
如果您对输出满意,请删除 echo
...
解释(逐行):
在
并打印 seconds_since_Unix_epoch (your_dir
中准确找到%T@
) 和文件(/dir)name 上的每个文件/目录单独一行- 按第一个字段 (seconds_since_Unix_epoch) 降序排序,丢弃前七行 - 从其余部分仅提取名称(第二个字段)
xargs
传递给新的find
逐个参数处理 (-n1
) 并使用fname
代表论点-maxdepth 0
将find
限制为fname
您可以将 minNrOfFiles 和 ageLimit 存储在 Bash-Variables 中,或者只需进行少量更改即可传递给脚本:
minNrOfFiles=7 # or $1
ageLimit=14 # or $2
更改:sed '1,'"$minNrOfFiles"'d'
和 -mtime +"$ageLimit"
关于Linux 清理目录脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12062236/