linux - 如何使用 for 循环评估函数参数

标签 linux shell ash

我想用 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...", 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 "$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/

相关文章:

c++ - 如何编译peercoin来生成Windows二进制文件?

bash - 从字符串中提取版本号

shell - Cloudformation 返回 RollbackInProgress

bash - 从嵌套的 for 循环中跳出

linux - 如何使子函数的返回导致父函数的返回?

c - 使用execv在C中拆分文件

linux - malloc() 是在内核空间吗?

ruby-on-rails - 大小超过 10 GB 的 error.log 或 access.log 是否会影响 RoR 应用程序的性能?

linux - 生成具有文件读取权限的用户列表

linux - 在 bash 中使用 {} 的字符串