访问 bash 命令行参数 $@ 与 $* [英] Accessing bash command line args $@ vs $*

查看:41
本文介绍了访问 bash 命令行参数 $@ 与 $*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多 SO 问题和 bash 教程中,我看到我可以通过两种方式访问​​ bash 脚本中的命令行参数:

In many SO questions and bash tutorials I see that I can access command line args in bash scripts in two ways:

$ ~ >cat testargs.sh 
#!/bin/bash

echo "you passed me" $*
echo "you passed me" $@

结果:

$ ~> bash testargs.sh arg1 arg2
you passed me arg1 arg2
you passed me arg1 arg2

$*$@ 有什么区别?
什么时候用前者,什么时候用后者?

What is the difference between $* and $@?
When should one use the former and when shall one use the latter?

推荐答案

引用特殊参数时出现的差异.让我来说明差异:

The difference appears when the special parameters are quoted. Let me illustrate the differences:

$ set -- "arg  1" "arg  2" "arg  3"

$ for word in $*; do echo "$word"; done
arg
1
arg
2
arg
3

$ for word in $@; do echo "$word"; done
arg
1
arg
2
arg
3

$ for word in "$*"; do echo "$word"; done
arg  1 arg  2 arg  3

$ for word in "$@"; do echo "$word"; done
arg  1
arg  2
arg  3

<小时>

关于引用重要性的另一个例子:注意arg"和数字之间有 2 个空格,但如果我没有引用 $word:


one further example on the importance of quoting: note there are 2 spaces between "arg" and the number, but if I fail to quote $word:

$ for word in "$@"; do echo $word; done
arg 1
arg 2
arg 3

在 bash 中,"$@" 是要迭代的默认"列表:

and in bash, "$@" is the "default" list to iterate over:

$ for word; do echo "$word"; done
arg  1
arg  2
arg  3

这篇关于访问 bash 命令行参数 $@ 与 $*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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