2014-04-01 67 views
2

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

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 
+0

'if test'find“$ f”-mmin + 30'' should be'[$(fi nd“$ f”-mmin +30)]' – fedorqui

回答

4
  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支持进程替换

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" 
+0

HI艾德里安,当我做第一个选项时,我得到以下错误。 'find:bad option -maxdepth find:[-H | -L]路径列表谓词列表' 理想情况下,我想将文件移动到另一个目录。我只是在这里回应以测试条件。 – user3484214

+0

啊,所以Solaris的'find'也没有'-maxdepth'。那么,你可以使用'find。 ! -名称 。 -prune -type f -mmin + 30'来模拟它。 –

+0

你也可以通过'find'去掉''''/''两个以上的斜杠来删除子目录中的结果。 -type f -mmin +30 | sed'/[/].*[/]/ d''但如果你有更深层次的文件/目录,这可能会更慢。 –

0

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

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 
+0

我同意,不幸的是,'stat'不是可移植的,并且在所有Solaris版本上都不可用(Solaris有自己的'truss'工具),所以这可能不起作用。 –

+0

@AdrianFrühwirth令人失望。只能在这种情况下解析'ls'的时间,尽管我认为你的解决方案更好。 – BroSlow

1

既然你是通过遍历目录,你可以尝试下面的命令,它会发现在过去的30分钟编辑日志类型结尾的文件。使用:

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

  • -mmin -30会给那些在最后30分钟

 

find ./ -type f -name "*.log" -mmin -30 -exec ls -l {} \; 
内更改过的所有文件
相关问题