构建包含空格的参数列表 [英] build argument lists containing whitespace
本文介绍了构建包含空格的参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 bash 中,可以转义包含空格的参数.
In bash one can escape arguments that contain whitespace.
foo "a string"
这也适用于命令或函数的参数:
This also works for arguments to a command or function:
bar() {
foo "$@"
}
bar "a string"
到目前为止一切顺利,但如果我想在调用 foo
之前操作参数怎么办?
So far so good, but what if I want to manipulate the arguments before calling foo
?
这不起作用:
bar() {
for arg in "$@"
do
args="$args \"prefix $arg\""
done
# Everything looks good ...
echo $args
# ... but it isn't.
foo $args
# foo "$args" would just be silly
}
bar a b c
那么当参数包含空格时如何构建参数列表?
So how do you build argument lists when the arguments contain whitespace?
推荐答案
(至少)有两种方法可以做到这一点:
There are (at least) two ways to do this:
使用数组并使用
"${array[@]}"
扩展它:
bar() {
local i=0 args=()
for arg in "$@"
do
args[$i]="prefix $arg"
((++i))
done
foo "${args[@]}"
}
那么,我们学到了什么?"${array[@]}"
对 ${array[*]}
什么是 "$@"
对 $*
.
So, what have we learned? "${array[@]}"
is to ${array[*]}
what "$@"
is to $*
.
或者如果你不想使用数组,你需要使用eval
:
Or if you do not want to use arrays you need to use eval
:
bar() {
local args=()
for arg in "$@"
do
args="$args \"prefix $arg\""
done
eval foo $args
}
这篇关于构建包含空格的参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文