[英]shell $@ variable assignment and iteration
function f() {
for arg; do
echo "$arg"
done
}
f 'hello world' 'second arg' '3rdarg'
this works fine: 这很好用:
hello world
second arg
3rdarg
but when do I assign $@
to some variable, and then it goes wrong: 但是什么时候我将$@
分配给某个变量,然后就出错了:
function f() {
local args="$@"
for arg in "$args"; do
echo "$arg"
done
}
hello world second arg 3rdarg
when I unquote the $args
, then each argument was split into single word: 当我取消引用$args
,每个参数都被分成单个单词:
hello
world
second
arg
3rdarg
Lastly, I wonder if there's a way to define variable like $@. 最后,我想知道是否有一种方法来定义像$ @这样的变量。 Any response will be appreciated. 任何回复将不胜感激。
You'll need to use an array: 你需要使用一个数组:
function f() {
local args=("$@") # values in parentheses
for arg in "${args[@]}"; do # array expansion syntax
echo "$arg"
done
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.