我想用 for
循环解析我的函数参数
func() {
for arg in $*; do
echo "$arg"
cone
}
如果我所有的参数都没有空格,这就可以正常工作
func "111" "222" "333"
但是对于带空格的参数它会失败
func "111" "222 222" "333"
最佳答案
不要使用$*
,而是使用"$@"
:
for arg in "$@" ; do
echo "$arg"
done
说明:如果没有双引号,$*
和$@
是相同的。但是,在双引号内,它们是不同的。详情参见man bash
中的“特殊参数”:
*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is,"$*"
is equivalent to"$1c$2c..."
, wherec
is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is,"$@"
is equivalent to"$1" "$2"
... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters,"$@"
and$@
expand to nothing (i.e., they are removed).
关于linux - 如何使用 for 循环评估函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28544621/