通过Bash传递命令行参数 [英] Passing command line arguments through Bash

查看:109
本文介绍了通过Bash传递命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在刷bash时(已经有一段时间了),我惊讶地发现执行此代码,另存为script.sh:

While brushing up on bash (it's been a while), I was surprised to notice that executing this code, saved as script.sh:

echo "Arg 0 to script.sh: $0"
echo "Arg 1 to script.sh: $1"
function echo_args
{
    echo "Arg 0 to echo_args: $0"
    echo "Arg 1 to echo_args: $1"
}
echo_args

像这样:

>> ./script.sh argument

输出以下内容:

Arg 0 to script.sh: ./script.sh
Arg 1 to script.sh: argument
Arg 0 to echo_args: ./script.sh
Arg 1 to echo_args:

我很惊讶地看到script.sh的$ 0是当$ 1的处理方式不同时,作为$ 0传递给echo_args。在我看来,应该两者都不是。

I was surprised to see that $0 of script.sh was passed as $0 to echo_args when $1 is not treated similarly. It seems to me it should be both or neither.

任何澄清都值得赞赏。

推荐答案

$ 0是bash中的特殊参数,始终求值为脚本名称,并在脚本开始处设置。

$0 is a "Special Parameter" in bash, which always evaluates to the name of the script, and is set at the start of the script. It looks like this also means it's somewhat global, since it can't be reassigned.

有关更多信息,这是一个很好的参考:

For more information, this is a pretty good reference:

http://bash.cyberciti.biz/guide/$0

这篇关于通过Bash传递命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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