测试是否有任何文件超过7天

时间:2018-04-22 17:10:24

标签: bash find

我有一个脚本可以查找文件夹中的文件,如果超过7天,则删除它们。但是,我有一点问题。

#!/bin/bash
BACKUPDIR=/home/vagrant/script/aerospike_backups
TIMESTAMP=$(date +%Y-%m-%d)
LOGPATH=/tmp/logs.txt
ADMINACC=email@example.com
EMEIL=rybka@gl.com
#Let's check existing backups, and if it's older than 7 days delete
find_old () {
     if [ -z $(find $BACKUPDIR -mtime +7 -print ) ]
       then
            return 10
              else
find $BACKUPDIR -mtime +7 -delete && echo "Backups deleted at $HOSTNAME on $TIMESTAMP" >  $LOGPATH

fi
} 

如果我使用./scriptname从终端使用空$ BACKUPDIR执行此脚本,则输入echo $? shell会按预期输出10个代码,因为不是7天之前的文件,或者根本没有文件。

但是在我添加更多条件之后如

if [[ $(find_old | echo $?) -gt 0 ]]
then
echo "Script return error code"
else
echo "all is ok"

该脚本为我提供了输出all is ok,但它真的不应该?怎么了?

1 个答案:

答案 0 :(得分:6)

将找到的文件存储在数组中然后将其删除,而不是两次调用<div class="mobile-nav-button" onclick="onMenuClick();"> <img id="menu-icon" src="Images/Home Page/MenuButton.png" /> <ul class="navigation-mobile"> <a href=""> <li class="nav-elements-mobile">Home</li> </a> <a href=""> <li class="nav-elements-mobile">Find a Team</li> </a> <a href=""> <li class="nav-elements-mobile">Contact Us</li> </a> <a href=""> <li class="nav-elements-mobile">Gallery</li> </a> <a href=""> <li class="nav-elements-mobile">Forms</li> </a> </ul> </div>会更好 - 这样,我们保证会删除我们找到的确切文件集,除了更有效率。

find

然后,将您的功能称为:

find_old() {
    while read -r -d '' file; do                  # read the output of find one file at a time
      files+=("$file")                            # append to the array
    done < <(find "$BACKUPDIR" -mtime +7 -print0) # generate NUL separated list of files
    if ((${#files[@]} == 0)); then
      # no files found
      return 10
    else
      printf '%s\0' "${files[@]}" | xargs -0 rm -f --
    fi
}

我已在您的代码中修复了一些问题:

  • 在扩展变量时引用变量非常重要。例如:find_old; exit_code=$? if ((exit_code > 0)) { echo "Script returned error code $exit_code" else echo "All is OK" fi 而不是find "$BACKUPDIR"
  • find $BACKUPDIR不是检查函数退出代码的方法;您需要直接检查if [[ $(find_old | echo $?) -gt 0 ]]

另见: