要了解你需要知道的4件事:
find
操作-exec
允许您在找到的文件和目录上应用命令。
BASH(1)
...
OPTIONS
...
-c If the -c option is present, then commands are read from
the first non-option argument command_string.
If there are arguments after the command_string, they
are assigned to the positional parameters, starting with $0.
...
If bash is started with the -c option, then $0 is set to the first
argument after the string to be executed, if one is present.
Otherwise, it is set to the filename used to invoke bash, as given
by argument zero.
在bash
,[email protected]
膨胀,所有位置参数($1
,$2
...)开始参数$1
:
如下-c
bash
选项记录。
在bash
函数中,位置参数是调用时传递给函数的参数。
所以,你的情况,对于每一个找到的文件或目录执行的命令是:
bash -c 'foo "[email protected]"' bash <the-file>
的位置参数,因此设置为:
$0 = bash
$1 = <the-file>
和bash
是问在这种情况下执行'foo "[email protected]"'
。 "[email protected]"
首先扩展为"<the-file>"
。所以,函数foo
被调用一个参数:"<the-file>"
。在功能foo
上下文中的位置参数是这样的:
$1 = "<the-file>"
echo "[email protected]"
和作为膨胀echo "<the-file>"
。
所有这些只是打印所有找到的文件或目录的名称。这几乎是如果你有任何的:
find . -exec echo {} \;
find . -print
find .
find
(用于find
版本接受最后一个)。
几乎就好像,因为如果文件或目录名称包含空格,这取决于您对find
的用法和引号,您将得到不同的结果。因此,如果您打算拥有更复杂的foo
函数,则应注意引号。例子:
$ touch "filename with spaces" plain
$ ls -1
filename with spaces
plain # 2 files
$ foo() { echo "[email protected]"; } # print arguments
$ find . -type f
./filename with spaces
./plain
$ find . -type f -exec bash -c 'foo "[email protected]"' bash {} \;
./filename with spaces
./plain
$ find . -type f -exec bash -c 'foo [email protected]' bash {} \;
./filename with spaces
./plain
3个find
命令显然做相同的,但:
$ bar() { echo $#; } # print number of arguments
$ wc -w < <(find . -type f)
4 # 4 words
$ find . -type f -exec bash -c 'bar "[email protected]"' bash {} \;
1 # 1 argument
1 # per file
$ find . -type f -exec bash -c 'bar [email protected]' bash {} \;
3 # 3 arguments
1 # 1 argument
随着find . -type f -exec bash -c 'bar "[email protected]"' bash {} \;
,第一个文件名被传递给函数bar
作为一个单独的参数,而在所有其他情况下,被视为3个独立的论点。
@Leon Ooops,谢谢。固定。 –
BTW,我收回我给予好评,因为海事组织,(更新)回答的第二部分没有解决OP的问题,因此可能有些误导 – Leon
@Leon没问题。我明白你的观点。我添加了第二部分,因为我怀疑真正的'foo'函数比OP显示的要复杂得多(否则,这将是无用的)。如果我没有错,它确实会有所作为......我试图让它更清晰一些。 –