Ris*_*ash 5 xargs shell-script
我有一个任务要删除所有超过 90 天的文件,也/dir/prd/log
就是从子目录中删除。我做了这个命令:
find /dir/prd/log* -mtime +90 | xargs rm
Run Code Online (Sandbox Code Playgroud)
然后我和一个 unix 的人交谈,他建议
find /dir/prd/log* -mtime +90 -print | xargs rm -f
Run Code Online (Sandbox Code Playgroud)
我只想知道他将“-print”和“-f”放在命令中的目的是什么。
Ste*_*itt 17
-f
告诉rm
从不提示(例如,当它遇到只读文件时)并忽略要求删除的丢失文件(而不是指示错误)。如果没有通过任何文件删除,它也不会抱怨。
在这里,根据xargs
实现rm
的标准输入将是来自find
或的管道/dev/null
,因此如果没有-f
, find 可能最终会从find
!的输出中读取这些提示的答案。
-print
是find
Linux 发行版和POSIX 兼容系统的默认操作,但可能需要在非常旧的 Unix 或类 Unix 系统上明确指定。
所以他的目的可能是让命令更加健壮和便携。您可以使用find
(超越 POSIX)的某些变体做得更好:
find /dir/prd/log -mtime +90 -print0 | xargs -0 rm -f
Run Code Online (Sandbox Code Playgroud)
避免包含“特殊”字符(包括空格、换行符、制表符、单引号、双引号、反斜杠)的文件名问题,如果您find
支持该-delete
操作,
find /dir/prd/log -mtime +90 -delete
Run Code Online (Sandbox Code Playgroud)
避免产生其他进程来执行删除(并避免一些竞争条件问题)。(请注意/dir/prd/log
,正如评论中所确认的那样,我在此处指定以符合您问题第一句话中所述的要求。)
使用 POSIX find
,您仍然可以xargs
通过要求find
自己运行来避免文件名解析rm
:
find /dir/prd/log -mtime +90 -exec rm -f '{}' +
Run Code Online (Sandbox Code Playgroud)
除了更加便携和可靠之外,它还避免了rm
从find
上面提到的 's 输出中读取提示答案的问题(rm
如果找不到文件,它也完全避免运行)。
如果/dir/prod/log
包含子目录,您需要过滤它们以避免错误消息,因为rm
无法删除它们:
find /dir/prd/log ! -type d -mtime +90 -exec rm -f '{}' +
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5083 次 |
最近记录: |