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

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

问题描述

您好所有shell和bash程序员那里。

Hello to all shell and bash programmers out there.

在很多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个空格,但如果我不引用$字:


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命令行参数$ @ $ VS *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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