检查 find 命令是否返回某些内容(在 bash 脚本中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13841452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check if find command return something (in bash script)
提问by Kupe3
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. However if no files are found, it creates corrupted tar file. I would like to wrap it in if..fi statement so id doesn't create empty/corrupted tar files.
如您所见,它创建了过去 24 小时内修改/创建的文件的备份。但是,如果没有找到文件,它会创建损坏的 tar 文件。我想将它包装在 if..fi 语句中,这样 id 就不会创建空/损坏的 tar 文件。
Can someone help me modify this script?
有人可以帮我修改这个脚本吗?
Thanks
谢谢
采纳答案by twalberg
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).
这样你就可以保证至少找到一个文件(而且它的大小最小)。
回答by Pilou
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
回答by John Kugelman
find /backups/www -type f -mtime -1 -exec tar uf /daily/backup-$today.tar {} +
Using -execis preferable to xargs. 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 -execcommand (in case there were more arguments to find).
使用-exec优于xargs. 不需要管道,它可以处理带有空格、换行符和其他不寻常字符的文件名,而无需额外工作。所述{}在端部是用于文件名的占位符和+标记所述的端部-exec命令(如果有更多的参数find)。
As a bonus it won't execute the command if no files are found.
作为奖励,如果没有找到文件,它不会执行命令。
回答by tripleee
xargs -rdoes nothing if there is no input.
xargs -r如果没有输入,则什么都不做。

