Linux 清理目录脚本

标签 linux bash scripting ls

我需要为 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...

解释(逐行):

  1. your_dir 中准确找到 并打印 seconds_since_Unix_epoch (%T@) 和文件(/dir)name 上的每个文件/目录单独一行
  2. 按第一个字段 (seconds_since_Unix_epoch) 降序排序,丢弃前七行 - 从其余部分仅提取名称(第二个字段)
  3. xargs 传递给新的 find 逐个参数处理 (-n1) 并使用 fname代表论点
  4. -maxdepth 0find 限制为 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/

相关文章:

html - 将日志文件 (*.txt) 转换为网络友好文件(*.html、*.jsp 等)的最佳方式?

linux - 意外的 EOF cronjob 错误

linux - sed 删除找到的最后一个匹配项之上的所有内容

linux - 对文件每一行的制表符分隔数字进行排序

bash - 从 Windows 的某个目录中启动 bash

scripting - Windows 应用商店中是否允许使用脚本应用程序?

linux - IntelliJ IC Linux 中是否可以进行外部拖放或复制/粘贴?

Linux Shell - 如何将变量分配给二进制表达式?

bash -/bin/bash printf 不适用于 C 以外的其他 LANG

c# - 如何在 Unity 中使用 UI.Text 作为预制件?