将带引号的字符串参数传递给 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.
如果您的 find
版本不支持 +
,那么您可以使用 \;
代替,但这会调用 ./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屋!