Background
I want to pass a list of filenames (listed via find
) containing spaces to my custom python script. Therefore, I set up find
to add quotes around each result:
find ./testdata -type f -printf "\"%p\" "
Result:
"./testdata/export (1).csv" "./testdata/export (2).csv" "./testdata/export (3).csv"
For the sake of this question, let's suppose my custom script (test.py
) does the following:
#!/usr/bin/python3
import sys
print(sys.argv)
Observations
Case 1:
Manually listing the quoted arguments.
Input: ./test.py "./testdata/export (1).csv" "./testdata/export (2).csv" "./testdata/export (3).csv"
Output: ['./test.py', './testdata/export (1).csv', './testdata/export (2).csv', './testdata/export (3).csv']
Case 2:
Using xargs
Input: find ./testdata -type f -printf "\"%p\" " | xargs ./test.py
Output: ['./test.py', './testdata/export (1).csv', './testdata/export (2).csv', './testdata/export (3).csv']
(I.e., output is the same as case 1)
Case 3:
Using backticks.
Input: ./test.py `find ./testdata -type f -printf "\"%p\" "`
Output: ['./test.py', '"./testdata/export', '(1).csv"', '"./testdata/export', '(2).csv"', '"./testdata/export', '(3).csv"']
Two things have changed:
"./testdata/export
and(1).csv"
are now two separate arguments.- the quotes remained part of the arguments
Questions
Why does the version with backticks behave differently?
Is there a way to still include the quotes with the backticks? I.e., make them behave the same as with
xargs
?
Remark
I really can't imagine what is going on here. One logical explanation could have been, that the output of the command in backticks will be treated as one big argument. But then, why is it splitted at the white spaces?
So the next best explanation seems to be that every white-space separated string is treated as a separate argument, without any regards to quoting. Is this correct? And if so, why do backticks have this strange behaviour? I guess this is not what we would want most of the time...
-exec
? – Jeff Schaller Sep 05 '19 at 15:20xargs
interprets quotes unless you use-d
. The shell doesn't do quote removal on the output of command substitution. Hence the difference. Thexargs
behaviour is what I'd usually not want. See also https://unix.stackexchange.com/a/523809/70524 – muru Sep 05 '19 at 15:23