要了解你需要知道的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顯示的要複雜得多(否則,這將是無用的)。如果我沒有錯,它確實會有所作爲......我試圖讓它更清晰一些。 –