红联Linux门户
Linux帮助

应该在find命令中使用-execdir代替-exec

发布时间:2016-12-17 11:37:10来源:blog.csdn.net/qidi_huang作者:Qidi_Huang
没事的时候读读 Linux 的 man 文档能学到不少新东西,注意到以前没注意过的细节。
 
比如刚才在看 find 命令的文档时就发现了下面这 2 段话:
-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  con‐structions  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 action; you should use the -execdir
option instead.
 
-execdir command {} +
Like  -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find.  This a much more secure method for invoking commands, as it avoids race conditions during resolution  of the  paths  to the matched files.  As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory.   If  you  use  this option,  you  must  ensure  that your $PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir.  The same applies to having  entries in $PATH which are empty or which are not absolute directory names.
 
注意看红字。
 
第 1 段话的意思是可以在 -exec 参数后接上花括号 {} 来表示每一个被找到的对象并执行操作,但每次执行操作的调用都是你执行 find 命令的目录,这可能导致竞态(find命令正在解析的路径和执行操作的命令使用的路径相同)的发生所以存在安全风险。因此应该使用 -execdir 参数替代 -exec。
 
第 2 段话的意思是 -execdir 参数的作用和 -exec 相同,区别在于前者每次对被找到的对象执行操作时都是在这些对象所在的目录下执行的,因此可以避免竞态。
 
同样的,也应该使用 -okdir 参数替代 -ok 参数使用。
 
本文永久更新地址:http://www.linuxdiyf.com/linux/26984.html