“{} \;”在Linux命令中意味着什么?

有时我看到以下命令:

find . -name  * -exec ls -a {} \; 

我被要求执行此操作。

什么是{} \; 这意味着什么

如果使用exec运行find{}会扩展为使用find的每个文件或目录的文件名(以便示例中的ls将每个找到的文件名作为参数获取 – 请注意它调用ls或者为每个命令指定一次的任何其他命令找到文件)。

分号; 结束exec执行的命令。 它需要用\来转义,以便你运行的shell在里面find它作为自己的特殊字符,而是将它传递给find

有关更多详细信息,请参阅此文章 。


此外, find提供了一些exec cmd {} +优化 – 当像这样运行时, find将找到的文件附加到命令的末尾,而不是每个文件调用一次(这样命令只运行一次,如果可能的话)。

如果以ls运行,行为的差异(如果不是效率)很容易引起注意,例如

 find ~ -iname '*.jpg' -exec ls {} \; # vs find ~ -iname '*.jpg' -exec ls {} + 

假设你有一些jpg文件( 路径足够短 ),结果是在第一种情况下每个文件一行,标准ls在后者的列中显示文件的行为。

find命令的联机帮助页 Manpage图标

 -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. 

所以这是解释:

{}表示“ find的输出”。 如同,“无论发现什么”。 find返回你正在寻找的文件的路径,对吧? 所以{}取而代之; 它是find命令所在的每个文件的占位符(取自此处 )。

\; 部分基本上是在说“好吧,我完成了我想要执行的命令”。

例:

假设我在一个充满.txt文件的目录中。 然后我跑:

 find . -name '*.txt' -exec cat {} \; 

第一部分, find . -name *.txt find . -name *.txt ,返回.txt文件的列表。 第二部分, -exec cat {} \; 将为find每个文件执行cat命令,所以cat file1.txtcat file2.txt等等。