【问题标题】:How to check if a file is older than 30 minutes in unix如何在 unix 中检查文件是否超过 30 分钟
【发布时间】:2014-05-11 22:14:43
【问题描述】:

我编写了一个脚本来遍历 Solaris 中的一个目录。该脚本查找超过 30 分钟的文件并回显。但是,无论文件有多旧,我的 if 条件总是返回 true。请有人帮忙解决这个问题。

for f in `ls -1`;
# Take action on each file. $f store current file name
do
  if [ -f "$f" ]; then
  #Checks if the file is a file not a directory
  if test 'find "$f" -mmin +30'
  # Check if the file is older than 30 minutes after modifications
  then
     echo $f is older than 30 mins
  fi
 fi
 done

【问题讨论】:

  • if test 'find "$f" -mmin +30' 应该是[ $(find "$f" -mmin +30) ]

标签: shell unix sh unix-timestamp solaris-10


【解决方案1】:

由于您正在遍历一个目录,您可以尝试以下命令,该命令将找到所有以在过去 30 分钟内编辑的日志类型结尾的文件。使用:

  • -mmin +30 将给出 30 分钟前编辑的所有文件

  • -mmin -30 将给出过去 30 分钟内发生更改的所有文件

 

find ./ -type f -name "*.log" -mmin -30 -exec ls -l {} \;

【讨论】:

    【解决方案2】:
    1. You should not parse the output of ls
    2. 您为每个不必要的缓慢文件调用find

    您可以将整个脚本替换为

    find . -maxdepth 1 -type f -mmin +30 | while IFS= read -r file; do
        [ -e "${file}" ] && echo "${file} is older than 30 mins"
    done
    

    或者,如果您在 Solaris 上的默认 shell 支持进程替换

    while IFS= read -r file; do
        [ -e "${file}" ] && echo "${file} is older than 30 mins"
    done < <(find . -maxdepth 1 -type f -mmin +30)
    

    如果您的系统上有GNU find 可用,那么整个事情可以在一行中完成:

    find . -maxdepth 1 -type f -mmin +30 -printf "%s is older than 30 mins\n"
    

    【讨论】:

    • 嗨,阿德里安,当我执行第一个选项时,出现以下错误。 find: bad option -maxdepth find: [-H | -L] path-list predicate-list 理想情况下,我想将文件移动到另一个目录中。我只是在这里呼应一下以测试 if 条件。
    • 啊,所以 Solaris 的 find 也没有 -maxdepth。好吧,你可以使用find . ! -name . -prune -type f -mmin +30 来模拟它。
    • 您还可以通过find . -type f -mmin +30 | sed '/[/].*[/]/d' 消除带有两个以上斜杠/ 的路径来消除子目录中的结果,但如果您有很多更深层次的文件/目录,这可能会更慢。
    • 那也没用。我发现了这个问题。 1. Solaris 没有-mmin 选项。它只有mtime。 2. 由于某种原因,我的test 命令不起作用,它总是返回true。但是,当我在 shell 中键入 find &lt;SOURCEDIR&gt; -name $FILENAME -type f -mtime +1 时,如果文件超过一天,它会返回文件的名称。
    【解决方案3】:

    另一种选择是使用 来检查时间。像下面这样的东西应该可以工作。

    for f in *
    # Take action on each file. $f store current file name
    do
      if [ -f "$f" ]; then
        #Checks if the file is a file not a directory
        fileTime=$(stat --printf "%Y" "$f")
        curTime=$(date +%s)
        if (( ( ($curTime - $fileTime) / 60 ) < 30 ))
          echo "$f is less than 30 mins old"
        then
          echo "$f is older than 30 mins"
        fi
      fi
    done
    

    【讨论】:

    • 我同意,不幸的是,stat 不是可移植的,也不是在所有 Solaris 版本上都可用(Solaris 有自己的工具,称为 truss)所以这可能行不通。
    • @AdrianFrühwirth 这令人失望。只能在这种情况下解析 ls 的时间,但我认为您的解决方案更好。
    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    相关资源
    最近更新 更多