Ten*_*igh 5 scripting bash files
我们的网络服务器最初由另一家公司维护。他们编写了一个简短的脚本来清除缓存文件。他们的文件有几行是这样写的:
/usr/bin/find /var/www/cache/blah/ |xargs /bin/rm -f >/dev/null 2>&1
Run Code Online (Sandbox Code Playgroud)
他们有什么理由不能只写:
/bin/rm -f /var/www/cache/blah/*
Run Code Online (Sandbox Code Playgroud)
删除文件?find当您需要特定标准时,我可以看到使用,但在这种情况下我似乎找不到。
我可以考虑为什么他们使用find+ 的一些原因xargs:
处理缓存文件过多的情况,如果只运行一个rm命令会导致错误。
Globbing*不会扩展隐藏文件。
递归工作。
但是这个find+xargs效率不高,因为当他们没有添加任何过滤器时,find结果将包含目录和文件。/bin/rm -f在目录上运行会导致错误,这就是为什么stderr和stdout被重定向到/dev/null. 对于那些名称包含特殊字符的文件,该命令也会失败。
改进的解决方案可以是:
find /var/www/cache/blah -type f -exec rm -f -- {} +
Run Code Online (Sandbox Code Playgroud)
这更有效,使用find、最小分叉rm和 POSIXly 完成所有工作。
There are a few differences in the behavior of the command lines:
find command line would delete files recursively in subdirectories, the rm command line wouldn't.
You need to consider whether or not you want to recurse.find command line would delete all files, if possible. The rm command line might skip files based on the shell's settings like GLOBIGNORE.
You need to consider whether or not there might be filenames that might be accidentally ignored in pathname expansion.find command line would succeed for any number of files. The rm command line might fail if the pathname expansion creates a command line that is too long (bigger than the system supports). Some systems have limits on this.
You need to consider how many files might need to be deleted.find command line ignores all output messages (using the redirections to >/dev/null). The rm command line prints the output messages.
You need to consider what should happen with the messages.If these differences do not matter to you, /bin/rm -f /var/www/cache/blah/* will work for you.
If only files are to be removed, and directories are to be retained, I would actually use
/usr/bin/find /var/www/cache/blah/ -not -type d -exec /bin/rm -f -- {} + >/dev/null 2>&1
Run Code Online (Sandbox Code Playgroud)
or
/usr/bin/find /var/www/cache/blah/ -type f -exec /bin/rm -f -- {} + >/dev/null 2>&1
Run Code Online (Sandbox Code Playgroud)
whatever suits your purpose, both have pros and cons.
-exec command {} +工作方式与 类似xargs,但效率稍高一些。在--防止rm翻倒,如果文件名中的一个开头-。此外,xargs以一种对文件名做出过多假设的方式使用。像空格这样的特殊字符实际上会破坏xargs. 需要类似的东西find ... -print0 | xargs -0,然后find -exec command {} +就简单多了。