Shell中的特殊参数
Variable & Description | |
---|---|
$0 | The filename of the current script. |
$n | These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on). |
$# | The number of arguments supplied to a script. |
$* | All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2. |
$@ | All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2. |
$? | The exit status of the last command executed. |
$$ | The process number of the current shell. For shell scripts, this is the process ID under which they are executing. |
$! | The process number of the last background command. |
$0
输出当前的文件名
1 |
|
$n
1 |
|
above function’s output is
arg1 == a
arg2 == b
arg3 == c
arg4 == d
$#
on behalf of the number of total input args.
$*
和 $@
- 在 Shell 脚本中,
$*
和$@
都用于引用脚本的所有参数。但它们在处理参数的方式上有细微的差别。$*
将所有的参数视为一个整体,它把所有的命令行参数看作一个单词。当被双引号"
包围时,"$*"
会将所有的参数拼接成一个字符串,各个参数之间用第一个参数($1
)中的IFS
(内部字段分隔符,Internal Field Separator)值来分隔。默认情况下,IFS
的值是空格、制表符和换行符。$@
将每个参数视为独立的个体。当被双引号"
包围时,"$@"
会将每个参数作为一个独立的字符串进行处理,这在很多情况下更符合实际需求,特别是在需要对每个参数进行单独操作时。在
ZSH
的shell脚本环境中,我没看出来这俩有啥区别,都是一样的输出,不管有么有添加双引号
1 |
|
上面的代码输出如下:
$*: hello shell world
$@: hello shell world
双引号中的$*: “hello shell world”
双引号中的$@: “hello shell world”
$?
- 当一个命令执行成功时,它通常会返回一个退出状态码 0。例如,在 Linux 系统中,如果使用
ls
命令列出目录内容并且操作成功,那么$?
的值就会是 0。 - 如果命令执行出现错误,会返回一个非零的退出状态码。不同的非零值可能代表不同类型的错误,具体的含义因命令而异。例如,命令找不到文件可能返回状态码 1,权限问题可能返回状态码 2 等。
1 |
|
上面代码输出:
0
Fri Dec 20 08:30:26 CST 2024
0
Shell中的特殊参数
https://jackiedai.github.io/2024/12/18/007unix_shell/004-Shell之特殊参数/