我在bash脚本中使用find
来清理一些超过一天的caching文件:
find /tmp/my_files_*.cache -mtime +1 -delete
问题是如果命令没有匹配任何文件,则会导致脚本的其余部分无法运行:
find: `/tmp/my_files_*.cache': No such file or directory
我目前正在通过追加|| true
解决它 || true
的命令,但这是不理想的,因为错误仍然出现在输出中,它允许脚本继续超过任何其他可能发生的错误。
我怎么知道如果没有文件匹配就可以?
用你原来的命令,实际上并不是find
除了你的shell之外的任何东西。
也就是说,当你跑步的时候
find /tmp/my_files_*.cache -mtime +1 -delete
如果有匹配的文件,shell的通配符function扩展了通配符,而实际的find
调用将如下所示:
find /tmp/my_files_1.cache /tmp/my_files_2.cache /tmp/my_files_3.cache -mtime +1 -delete
(这可能很容易成为一个非常长的命令,在某些情况下,这本身就是一个问题)
当没有匹配时,通配符按原样传递,因此find
调用将如下所示:
find /tmp/my_files_*.cache -mtime +1 -delete
并且像大多数程序一样运行find
不会为path参数自行进行任何通配符扩展,所以它会尝试查找名为/tmp/my_files_*.cache
的文件/目录,从而导致错误。
正如Ipor Sircer指出的那样,使用find
的更习惯的方式是给它一个基本path,让find
通过目录内容来查看,并根据需要应用filter。
像这样的东西应该匹配你想要做的事情:
find /tmp -maxdepth 1 -name "my_files_*.cache" -mtime +1 -delete
find /tmp -name "*.cache" -mtime +1 -delete
如果你不在乎是否有文件需要删除,那就不要费心去testing成功与否,只要丢掉任何错误:
find/tmp/my_files_*.cache -mtime +1 -delete 2> / dev / null