Passing command line arguments through Bash

大城市里の小女人 提交于 2019-12-23 17:28:00

问题


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

like this:

>> ./script.sh argument

output this:

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:

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.

Any clarification is appreciated.


回答1:


$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



来源:https://stackoverflow.com/questions/25467253/passing-command-line-arguments-through-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!