【shell】find -exec 命令

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010900754/article/details/83020378

格式如下:

find dir -exec cmd \;  

但是通常,后面的cmd命令需要处理find查询到的文件,所以需要把文件名传给cmd。这时,可以使用占位符{}来表示find到的文件名。

那么格式变为了:

find dir -exec cmd {} \;

上面的形式,shell会每一个find到的文件去执行一次cmd命令。如果想让find到的文件一次性执行完cmd命令,那么可以使用"+"号代替“\;”

find dir -exec cmd {} +

例子:

⇒  ls -l
total 32
drwxr-xr-x  5 miracle  staff  170 11 23  2017 123
-rw-r--r--  1 miracle  staff    4 11 24  2017 a.txt
-rw-r--r--@ 1 miracle  staff    5 11 23  2017 b.txt
-rw-r--r--@ 1 miracle  staff    5 11 23  2017 c.txt
-rwxrwxrwx  1 miracle  staff  106 11 23  2017 t.sh

然后:

⇒  find . -maxdepth 1 -type f -name "*.txt" -exec echo "hello" \;
hello
hello
hello

⇒  find . -maxdepth 1 -type f -name "*.txt" -exec echo {} \;
./a.txt
./b.txt
./c.txt

⇒  find . -maxdepth 1 -type f -name "*.txt" -exec echo {} +
./a.txt ./b.txt ./c.txt

这便是上面三种形式的例子。

另外再解释下-exec 后面的\;和+。

一个-exec只能执行一个命令,而且必须在命令后面加上终结符,终结符有两个,“;”和“+”。

其中“;”表示一个-exec 的 cmd命令结束。而”+“开始已经说过了。

为什么必须有终结符???

因为一个find后面可以有多个-exec cmd,所以必须要有终结符分割他们。

比如:

⇒  find . -maxdepth 1 -type f -name "*.txt" -exec echo {} \; -exec echo {} +
./a.txt
./b.txt
./c.txt
./a.txt ./b.txt ./c.txt

上面的命令就有两个-exec。如果,没有加终结符,第二个命令就无法和第一个相区别了,比如:

⇒  find . -maxdepth 1 -type f -name "*.txt" -exec echo {} -exec echo {} \;
./a.txt -exec echo ./a.txt
./b.txt -exec echo ./b.txt
./c.txt -exec echo ./c.txt

第二个-exec echo {} 成为了第一个echo的输出内容。

所以,每一个-exec 都需要终结符。

第二个问题,为什么要加“\”?

这是因为,“;”是shell的命令分隔符,如果只有“;”,那么这条命令就会被shell截断。

比如:

⇒  find . -maxdepth 1 -type f -name "*.txt" -exec echo {} ;

最终会报:find: -exec: no terminating ";" or "+"

因为shell发现了末尾的“;”,就把前面的当成了一个命令,但是,因为没有终结符,所以无法执行。所以要加一个转义符”\“,让shell知道这个”;“有特殊含义。

猜你喜欢

转载自blog.csdn.net/u010900754/article/details/83020378
今日推荐