将带引号的字符串参数传递给bash脚本

时间:2014-03-10 17:32:24

标签: string bash arguments

我无法在这里或其他任何地方找到这个看似简单问题的解决方案。我想获取嵌套目录中所有文件的路径,在它们周围添加引号,并在bash脚本中循环它们。目录名称和文件中可以包含空格。到目前为止,我没有尝试过任何正常引用的路径字符串总是在空格处被分解。

test.sh

for var in "$@"
do
    echo "$var"
done

我尝试从每行一个路径的文件中读取,包括单引号和双引号:

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`

并使用引用路径,单引号和双引号之间的空格命令替换:

./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

只需从命令行回显引用路径即可得到所需的结果。脚本中缺少什么可以将参数解析为完整的字符串?

1 个答案:

答案 0 :(得分:4)

请改为:

find "nested directory with spaces" -type f -exec ./test.sh {} +

这将使用多个参数调用test.sh,而不会拆分文件名中的空格。

如果您的find版本不支持+,那么您可以改为使用\;,但会为每个参数调用./test.sh一次。

例如,给定脚本:

#!/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
相关问题