简体   繁体   English

检查find命令是否返回了某些内容(在bash脚本中)

[英]check if find command return something (in bash script)

i have the following bash script on my server: 我的服务器上有以下bash脚本:

today=$(date +"%Y-%m-%d")
find /backups/www -type f -mtime -1|xargs tar uf /daily/backup-$today.tar

as you can see it creates backups of files modified/created in the last 24h. 如您所见,它创建了过去24小时内修改/创建的文件的备份。 However if no files are found, it creates corrupted tar file. 但是,如果找不到文件,则会创建损坏的tar文件。 I would like to wrap it in if..fi statement so id doesn't create empty/corrupted tar files. 我想将其包装在if..fi语句中,以便id不会创建空的/损坏的tar文件。

Can someone help me modify this script? 有人可以帮我修改此脚本吗?

Thanks 谢谢

You can check if result is ok then check if result is empty : 您可以检查结果是否正常,然后检查结果是否为空:

   today=$(date +"%Y-%m-%d")
   results=`find /backups/www -type f -mtime -1`


    if [[ 0 == $? ]] ; then
     if [[ -z $results ]] ; then
      echo "No files found"
     else
      tar uf /daily/backup-$today.tar $results
     fi
    else
     echo "Search failed"
    fi
find /backups/www -type f -mtime -1 -exec tar uf /daily/backup-$today.tar {} +

Using -exec is preferable to xargs . 使用-execxargs更可取。 There's no pipeline needed and it will handle file names with spaces, newlines, and other unusual characters without extra work. 不需要管道,它无需额外的工作即可处理带有空格,换行符和其他不寻常字符的文件名。 The {} at the end is a placeholder for the file names, and + marks the end of the -exec command (in case there were more arguments to find ). 末尾的{}是文件名的占位符,而+标记-exec命令的末尾(如果要find参数更多)。

As a bonus it won't execute the command if no files are found. 另外,如果找不到文件,它将不会执行命令。

One relatively simple trick would be this: 一个相对简单的技巧是:

today=$(date +"%Y-%m-%d")
touch /backups/www/.timestamp
find /backups/www -type f -mtime -1|xargs tar uf /daily/backup-$today.tar

That way you're guaranteed to always find at least one file (and it's minimal in size). 这样一来,您可以确保始终找到至少一个文件(并且该文件的大小最小)。

如果没有输入, xargs -r不执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM