Linux清理目录脚本

时间:2012-08-21 20:06:22

标签: 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,但我无法弄清楚如何将它们放在一起。

1 个答案:

答案 0 :(得分:1)

#!/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. find完全位于your_dir中,并在单独的行中打印seconds_since_Unix_epoch(%T@)和每个文件/目录的文件(/ dir)名称
  2. 按第一个字段排序(seconds_since_Unix_epoch)降序,抛出前七行 - 从其余部分提取名称(第二个字段)
  3. xargs传递给新的find进程逐个参数(-n1)并使用fname来表示参数
  4. -maxdepth 0find限制为fname
  5. 您可以将minNrOfFiles和ageLimit存储在Bash-Variables中,或者只需进行一些更改即可传入脚本:

    minNrOfFiles=7 # or $1
    ageLimit=14    # or $2
    

    更改:sed '1,'"$minNrOfFiles"'d'-mtime +"$ageLimit"

相关问题