构建包含空格的参数列表 [英] 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"
到目前为止好,但是如果我想之前调用操作的参数是什么富
?
这不工作:
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:
(1)使用一个数组,并使用展开$ {数组[@]}
:
(1.) Use an array and expand it using "${array[@]}"
:
bar() {
local i=0 args=()
for arg in "$@"
do
args[$i]="prefix $arg"
((++i))
done
foo "${args[@]}"
}
所以,我们学到了什么? $ {数组[@]}
为 $ {数组[*]}
什么$ @
到 $ *
。
(2)或者,如果你不想用你需要使用数组评估
:
(2.) 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屋!
查看全文