【问题标题】:Printing the shell find and remove command to screen and log file将 shell 查找和删除命令打印到屏幕和日志文件
【发布时间】:2016-06-13 14:36:25
【问题描述】:

我有一个脚本可以在指定目录中查找早于 x 天的日志文件并将其删除。

find $LOG_ARCHIVE/* -mtime +$DAYS_TO_KEEP_LOGS -exec rm -f {} \;

这按预期工作,但我希望可以选择将处理打印到屏幕和日志文件,以便我知道哪些文件(如果有)已被删除。我尝试在末尾附加tee,但没有成功。

find $LOG_ARCHIVE/* -mtime +$DAYS_TO_KEEP_LOGS -exec rm -fv {} \; | tee -a $LOG

【问题讨论】:

    标签: shell


    【解决方案1】:

    有多种方法可以完成任务。

    一种可能性是简单地运行find 两次:

    find "$LOG_ARCHIVE" -mtime +"$DAYS_TO_KEEP_LOGS" -print > "$LOG"
    find "$LOG_ARCHIVE" -mtime +"$DAYS_TO_KEEP_LOGS" -exec rm -f {} +
    

    另一种可能性是使用tee 以及(GNU 扩展)-print0find-0xargs

    find "$LOG_ARCHIVE" -mtime +"$DAYS_TO_KEEP_LOGS" -print0 |
    tee "$LOG" |
    xargs -0 rm -f
    

    在此版本中,日志文件将在每个文件名的末尾包含空字节。如果您不介意可能的歧义,可以安排用换行符替换它们:

    find "$LOG_ARCHIVE" -mtime +"$DAYS_TO_KEEP_LOGS" -print0 |
    tee >(tr '\0' '\n' >"$LOG") |
    xargs -0 rm -f
    

    这使用 Bash(和 Korn shell)process substitution 将日志文件通过 tr 将空字节 '\0' 映射到换行符 '\n'

    另一种方法是编写一个小的自定义脚本(称之为remove-log.sh):

    printf '%s\n' "$@" >> "$LOG"
    rm -f "$@"
    

    然后使用:

    find "$LOG_ARCHIVE" -mtime +"$DAYS_TO_KEEP_LOGS" -exec bash remove-log.sh {} +
    

    请注意,脚本需要查看$LOG 的值,因此必须将其导出为环境变量。您可以通过显式传递日志名称来避免这种情况:

    logfile="$1"
    shift
    printf '%s\n' "$@" >> "$logfile"
    rm -f "$@"
    

    加:

    find "$LOG_ARCHIVE" -mtime +"$DAYS_TO_KEEP_LOGS" -exec bash remove-log.sh "$LOG" {} +
    

    请注意,这两个都使用>> 追加,因为脚本可能会被多次调用(尽管它可能不会被调用)。在运行find 命令之前,您有责任确保日志文件为空。

    请注意,我从find 的路径参数中删除了/*;它不是真的需要。您可能需要添加 -type f 以确保仅删除文件。 + 是 POSIX 2008 规范中 find 的一个特性,它使 find 的行为更像 xargs,而无需显式使用 xargs

    【讨论】:

      【解决方案2】:
      find $LOG_ARCHIVE/* -mtime +$DAYS_TO_KEEP_LOGS -exec sh -c 'echo {} |tee -a "$LOG"; rm -f {}' \;
      

      试试看是否有效。

      【讨论】:

      • 发现:`-exec' 缺少参数
      • @algorhythm 我猜你错过了尾随的反斜杠分号,或者你可能错过了一些引号。
      • 啊,是的,反斜杠被剪掉了。现在没有错误,但文件也没有被删除
      • @algorhythm 你有输出吗? $LOG 文件呢?
      猜你喜欢
      • 2014-01-12
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 2021-03-12
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      相关资源
      最近更新 更多