What do $? $0 $1 $2 mean in shell script? [duplicate]

笑着哭i 提交于 2019-11-26 05:20:21

问题


This question already has an answer here:

  • What are the special dollar sign shell variables? 4 answers

I often come across $? $0 $1 $2 etc.... in shell scripting, what I know is that $? returns the exit status of the last command

echo \"this will return 0\"
echo $?

but what do the others do? what are they called and is there more? perhaps like $3 $4 $5 ...


回答1:


These are positional arguments of the script.

Executing

./script.sh Hello World

Will make

$0 = ./script.sh
$1 = Hello
$2 = World

Note

If you execute ./script.sh, $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh.




回答2:


They are called the Positional Parameters.

3.4.1 Positional Parameters

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).

When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.



来源:https://stackoverflow.com/questions/29258603/what-do-0-1-2-mean-in-shell-script

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