如何动态构建包含bash中空格的参数

问题描述 投票:0回答:1

我有一个脚本find-files,该脚本生成的路径可以包含行中的空格

/foo bar
/abc

我想将这些路径转换为传递给另一个命令cmd的参数,如下所示:

cmd -f "/foo bar" -f "/abc"

我尝试过此

cmd $(find-files | sed 's/^/-f /')

但是它传递包含空格的路径作为多个参数。

并且如果我引用替换,则整个字符串将作为单个参数传递。

正确的做法是什么?

顺便说一句,这与asked here提示eval的问题不同。 eval根本无法处理空格。

bash shell command-line
1个回答
0
投票

将所有文件名放入数组。

lst=( "/foo bar" /abc ) # quote as necessary

然后使用printf插入-f

cmd $( printf ' -f %s' "${lst[@]}" ) # leading space helps

例如

$: echo $( printf ' -f %s' "${lst[@]}" )
-f /foo bar -f /abc

[-f前面的前导空格简化了一点。没有它,您将得到:

$: echo $( printf '-f %s' "${lst[@]}" )
bash: printf: -f: invalid option
printf: usage: printf [-v var] format [arguments]
© www.soinside.com 2019 - 2024. All rights reserved.