Linux find命令-exec参数用法解析

发布时间:2020-11-27编辑:脚本学堂
本文介绍了linux find命令中exec参数的用法,删除所有临时文件,需要的朋友参考下。

linuxcmd/ target=_blank class=infotextkey>linux命令find + -exec参数,例如:
 

find /usr/local/backups -mtime +10 -name "*.*" -exec rm -rf {} /;

查看find命令的帮助文档:man find
其中的exec选项解释:     
(1)-exec command ;
       Execute  command;  true if 0 status is returned.  All following arguments to find are taken to be arguments to the command until an  argument  consisting of ';' is encountered.  The string '{}' is replaced by the current file name being processed everywhere it occurs in the arguments to  the  command,  not just  in  arguments where it is alone, as in some versions of find.  Both of  these constructions might need to be escaped (with a '/') or quoted to  protect  them  from expansion by the shell.  See the EXAMPLES section for examples of the use of the '-exec' option.  The specified command  is  run  once for  each  matched file.  The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec option; you should use the -execdir option instead.
 
(2)-exec command {} +
       This  variant of the -exec option runs the specified command on the selected files, but the command line is built by appending each selected file name at  the  end;  the  total number of invocations of the command will be much less than the number of matched files.  The command line is  built  in  much  the same  way that xargs builds its command lines.  Only one instance of '{}' is allowed within the command.  The command is executed in the starting directory.
 
(1); (分号)表示command命令参数的结束,特别强调,对于不同的系统,直接使用分号可能会有不同的意义, 所以使用转义符/在分号前明确说明。
(2){}表示文件名,也就是find前面处理过程中过滤出来的文件,用于command命令进行处理。

例子:
删除所有临时文件
 

find / -name "*.tmp" -exec rm -rf {} /;

查找10天前的dmp文件,并将文件copy到/root/davetmp/目录:
 

find /root/py -mtime +10 -name "*.dmp" -exec cp {} /root/davetmp/  /;