【问题标题】:Passing a variable to find -mtime command传递一个变量来查找 -mtime 命令
【发布时间】:2020-06-04 15:06:02
【问题描述】:

我目前正在尝试编写一个脚本,该脚本将在 X 天后使用 find 命令删除文件。

使用以下命令时,它可以正常工作并成功删除任何超过 10 天的文件。

find /path/to/file/to/delete -type f -mtime +10 -exec rm -f {} \;

但是,当尝试使用以下命令将其作为脚本参数传递时:

./delete-old-files.sh 10

find /path/to/file/to/delete -type f -mtime +$1 -exec rm -f {} \;

我遇到了这个错误:

find: invalid argument `+' to `-mtime'

我应该用某种方法包装变量以确保它不会妨碍-mtime 参数吗?

【问题讨论】:

  • 你可以 '-exec rm -f {}' 而不是 '-print -delete' 并且对于未初始化的 var 你可以使用${var:-default}${1:-0}
  • $1 参数到达您的find 命令时的内容是什么?在find 命令之前的行中插入printf '%q\n' "$1";exit,然后再次运行您的脚本。它将打印您的 $1 参数的实际内容。
  • 您能否向我们展示有关您的脚本的更多详细信息(即显示脚本的大部分内容)。我有一种模糊的感觉,$1 不再是你所期望的那样。
  • delete-old-files(){ find . -type f -mtime +$1 -exec echo rm -f {} \; ; } 为我工作,所以您需要展示整个脚本

标签: bash shell


【解决方案1】:

在您的脚本中运行带参数的 delete-old-files(),否则 local $1 保持为空,因为它与 global $1 的不同你的脚本

./delete-old-files.sh 10  

为了更好地理解这个例子,global $1 被传递给 local $2 作为参数。你可以看到区别 local $1 是 path 而 global $1 是 mtime

#!/bin/bash

delete-old-files() {
  local folder
  # just some tests to make sure find will run on folder and mtime is set
  [ "$2" ] && [ -e "$1" ] && folder="$(realpath "$1")"
  [ -d "$folder" ] || return 1

  find "$folder" -maxdepth 1 -type f -mtime +$2 -print #-delete
  return $?
}

delete-old-files /path/to/file/to/delete $1 || exit $?

改进:如果您不想硬编码path,也可以从参数中读取。您可以遍历位置参数,将 mtime 读入 var 并删除所有无效路径
(见answer

使用剩余参数调用find(适用于非平凡的文件夹名称)

# script
find "$@" -maxdepth 1 -type f -mtime +$days -print #-delete

使用任意数量的文件夹运行脚本(无功能)

./delete-old-files.sh ~/dir1 "path/to/dir 2" 10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 2011-02-19
    • 2019-02-16
    • 2017-12-15
    相关资源
    最近更新 更多