Bash特殊变量(Bash Special Variables)

$#

Number of command-line arguments.

传递给脚本或函数的参数个数。


$_

The underscore variable is set at shell startup and contains the absolute file name of the shell or script being executed as passed in the argument list. Subsequently, it expands to the last argument to the previous command, after expansion. It is also set to the full pathname of each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file.

$_保存的是命令(或脚本)的最后一个参数。


$-

A hyphen expands to the current option flags as specified upon invocation, by the set built-in command, or those set by the shell itself (such as the -i).

使用Set命令设定的Flag一览


$?

Exit value of last executed command.

$? 可以获取上一个命令的退出状态。所谓退出状态,就是上一个命令执行后的返回结果。退出状态是一个数字,一般情况下,大部分命令执行成功会返回 0,失败返回 1。不过,也有一些命令返回其他值,表示不同类型的错误。$? 也可以表示函数的返回值。当我们执行完一个命令的时候,都可以用 echo $? 来查看命令的退出码 exit code(或称返回码),从而判断命令是否正确执行。可以理解为命令的返回值(后面我们学到Bash函数的时候,也会用它来做返回值),但是与其他语言不同的是它只是一个固定的8位二进制数,也就是说它的范围是0-255。并没有其他语言中返回值那么丰富的功能。


$$

Process number of the shell.

$$ 表示当前Shell进程的ID,即pid


$!

Process number of last background command.

Shell最后运行的后台Process的PID


$0

First word; that is, the command name. This will have the full pathname if it was found via a PATH search.

数字变量$0,保存的是这个执行脚本的名称,


$n

Individual arguments on command line (positional parameters). The Bourne shell allows only nine parameters to be referenced directly (n = 1–9); Bash allows n to be greater than 9 if specified as ${n}.

其他的数字1到n保存该脚本运行时的第1到第n个参数。


$*, $@

All arguments on command line ($1 $2 …).

@,* 就是所有变量。从这里来看似乎两者没有差别。但是其实是不同的,通配符*将所有参数视作一个变量,而@则可以理解为所有参数的集合。


“$*”

All arguments on command line as one string (“$1 $2…”). The values are separated by the first character in $IFS.

$*将所有位置参数当做一个字符串输出;


“$@”

All arguments on command line, individually quoted (“$1” “$2” …).

$@将每个位置参数当做独立的元素处理,带空格的参数也当做一个整体。


参考资料

=============

https://www.mylinuxplace.com/bash-special-variables/

https://blog.csdn.net/guodongxiaren/article/details/39544805

http://xstarcd.github.io/wiki/shell/shell_special_variables.html

https://blog.csdn.net/guodongxiaren/article/details/39544805

posted on 2020-12-14 13:20  中道学友  阅读(298)  评论(0编辑  收藏  举报

导航

技术追求准确,态度积极向上