1. 程式人生 > >應該在find命令中使用-execdir代替-exec

應該在find命令中使用-execdir代替-exec

    沒事的時候讀讀 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 引數使用。