"$@" 和有什么不一样?和“$*"在 Bash 中? [英] What is the difference between "$@" and "$*" in Bash?

查看:29
本文介绍了"$@" 和有什么不一样?和“$*"在 Bash 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,它们都存储了所有命令行参数.

It seems to me that they both store all the command-line arguments.

那两者有区别吗?

推荐答案

区别很微妙;"$*" 创建一个由 $IFS 变量分隔的参数,而 "$@" 将扩展为单独的参数.例如,考虑:

The difference is subtle; "$*" creates one argument separated by the $IFS variable, while "$@" will expand into separate arguments. As an example, consider:

for i in "$@"; do echo "@ '$i'"; done
for i in "$*"; do echo "* '$i'"; done

当使用多个参数运行时:

When run with multiple arguments:

./testvar foo bar baz 'long arg'
@ 'foo'
@ 'bar'
@ 'baz'
@ 'long arg'
* 'foo bar baz long arg'

欲知更多详情:

http://www.gnu.org/software/bash/manual/bashref.html#Special-Parameters

$*

扩展到位置参数,从 1 开始.当扩展发生在双引号内时,它扩展为单个单词,每个参数的值由 IFS 特殊变量的第一个字符分隔.也就是说,"$*" 等价于 "$1c$2c...",其中 c 是 IFS 变量值的第一个字符.如果未设置 IFS,则参数以空格分隔.如果 IFS 为 null,则连接参数时不插入分隔符.

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.

$@

扩展到位置参数,从 1 开始.当扩展发生在双引号内时,每个参数都扩展为一个单独的词.即 "$@" 等价于 "$1" "$2" .... 如果单词内出现双引号展开,则第一个展开参数与原词的开头部分连接,最后一个参数的扩展与原词的最后部分连接.当没有位置参数时,"$@"$@ 扩展为空(即,它们被删除).

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).

这篇关于"$@" 和有什么不一样?和“$*"在 Bash 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆