shell $@ 变量赋值和迭代 [英] shell $@ variable assignment and iteration
本文介绍了shell $@ 变量赋值和迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
function f() {
for arg; do
echo "$arg"
done
}
f 'hello world' 'second arg' '3rdarg'
这很好用:
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
当我取消引用 $args
时,每个参数都被拆分为一个单词:
when I unquote the $args
, then each argument was split into single word:
hello
world
second
arg
3rdarg
最后,我想知道是否有一种方法可以定义像 $@ 这样的变量.任何回应将不胜感激.
Lastly, I wonder if there's a way to define variable like $@. Any response will be appreciated.
推荐答案
你需要使用一个数组:
function f() {
local args=("$@") # values in parentheses
for arg in "${args[@]}"; do # array expansion syntax
echo "$arg"
done
}
这篇关于shell $@ 变量赋值和迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文