为什么 find 命令的-exec 选项需要反斜杠和分号?

我已经开始在 Linux 终端中组合不同的命令。我想知道为什么反斜杠和分号是命令所必需的,比如:

find ./ -name 'blabla' -exec cp {} ./test \;

当简单的 cp 命令只是:

cp randomfile ./test

没有 \;

它们是清楚地表明命令的结束,还是仅仅在文档中要求这样做?基本原则是什么?

16584 次浏览

from "man find":

All following arguments to find are taken to be arguments to the command until an argument consisting of ';' is encountered.

find needs to know when the arguments of exec are terminated. It is natural to terminate a shell command with ; because also the shell uses this character. For the very same reason such a character must be escaped when inserted through the shell.

The backslash before the semicolon is used, because ; is one of list operators (or &&, ||) for separating shell commands. In example:

command1; command2

The find utility is using ; or + to terminate the shell commands invoked by -exec.

So to avoid special shell characters from interpretation, they need to be escaped with a backslash to remove any special meaning for the next character read and for line continuation.

Therefore the following example syntax is allowed for find command:

find . -exec echo {} \;
find . -exec echo {} ';'
find . -exec echo {} ";"
find . -exec echo {} \+
find . -exec echo {} +

See also: