引用传递字符串参数为一个bash脚本 [英] Passing quoted string arguments to a bash script
问题描述
我一直没能在这里或其他地方找到一个解决这个看似简单的问题。我想在嵌套目录中的所有文件的路径,在bash脚本添加引号在他们身边,并遍历它们。目录名和文件可以在他们的空格。到目前为止,我没有尝试过正常工作。带引号的路径字符串总是在空格就会破碎。
I have not been able to find a solution to this seemingly simple problem here or anywhere else. I want to get the paths of all files in a nested directory, add quotes around them, and loop through them in a bash script. Directory names and files can have white spaces in them. So far nothing I tried works properly. The quoted path strings always get broken up at the spaces.
test.sh
for var in "$@"
do
echo "$var"
done
我想从文件中读取每行一个路径,单引号和双引号:
I tried reading from a file with one path per line, both single and double quotes:
find "nested directory with spaces" -type f | sed -e 's/^/"/g' -e 's/$/"/g' | tr '\n' '\n' > list.txt # double quotes
./test.sh `cat list.txt`
find "nested directory with spaces" -type f | sed -e 's/^/'\''/g' -e 's/$/'\''/g' | tr '\n' ' ' > list.txt # single quotes
./test.sh `cat list.txt`
和带引号的路径,单引号和双引号之间的空间命令替换:
and command substitution with a space between quoted paths, single and double quotes:
./test.sh `find "nested directory with spaces" -type f | sed -e 's/^/"/g' -e 's/$/"/g' | tr '\n' ' '` # double quotes
./test.sh `find "nested directory with spaces" -type f | sed -e 's/^/'\''/g' -e 's/$/'\''/g' | tr '\n' ' '` # single quotes
仅仅附和在命令行中带引号的路径给出期望的结果。现在缺少的脚本,它可以解决参数到完整的字符串?
Simply echoing a quoted path from the command line gives the desired result. What is missing in the script that can resolve the arguments into complete strings?
推荐答案
像这样做,而不是:
find "nested directory with spaces" -type f -exec ./test.sh {} +
这将调用 test.sh
使用多个参数,在不分裂名的空间。
This will call test.sh
with multiple arguments, without splitting the spaces in the filenames.
如果你的版本找到
不支持 +
,那么你可以使用 \\;
代替,但将调用 ./ test.sh
一次为每个参数
If your version of find
doesn't support +
, then you can use \;
instead, but that will call ./test.sh
once for each argument.
例如,给出脚本:
#!/bin/sh
echo start
for i; do
echo file: "$i"
done
+
和之间的区别\\;
:
$ find a\ b.txt date.txt -exec ./test.sh {} +
start
file: a b.txt
file: date.txt
$ find a\ b.txt date.txt -exec ./test.sh {} \;
start
file: a b.txt
start
file: date.txt
这篇关于引用传递字符串参数为一个bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!