如何使用 for 循环评估函数参数
How to evaluate function arguments with for loop
我想用 for
循环解析我的函数参数
func() {
for arg in $*; do
echo "$arg"
cone
}
如果我所有的参数都没有空格,这就可以正常工作
func "111" "222" "333"
但是对于带空格的参数它会失败
func "111" "222 222" "333"
将此函数与 "$@"
一起使用,而不是不带引号的 $*
:
func() { for arg in "$@"; do echo "$arg"; done; }
然后将其命名为:
func "111" "222 222" "333"
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 "cc..."
, where c
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 "" ""
... 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).
我想用 for
循环解析我的函数参数
func() {
for arg in $*; do
echo "$arg"
cone
}
如果我所有的参数都没有空格,这就可以正常工作
func "111" "222" "333"
但是对于带空格的参数它会失败
func "111" "222 222" "333"
将此函数与 "$@"
一起使用,而不是不带引号的 $*
:
func() { for arg in "$@"; do echo "$arg"; done; }
然后将其命名为:
func "111" "222 222" "333"
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"cc..."
, 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"" ""
... 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).