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
2
3
4
TEST_0() {
echo "current name --- $0" # current name --- 003_sepcial_vars.sh
}
TEST_0

$n

1
2
3
4
5
6
7
8
#!/bin/sh
TEST(){
echo "arg1 == $1"
echo "arg2 == $2"
echo "arg3 == $3"
echo "arg4 == $4"
}
TEST a b c d

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
2
3
4
5
6
TEST_6() {
echo "\$*: $*"
echo "\$@: $@"
echo '双引号中的\$*: "'$*'"'
echo '双引号中的\$@: "'$@'"'
}

上面的代码输出如下:

$*: hello shell world

$@: hello shell world
双引号中的$*: “hello shell world”
双引号中的$@: “hello shell world”

$?

  • 当一个命令执行成功时,它通常会返回一个退出状态码 0。例如,在 Linux 系统中,如果使用ls命令列出目录内容并且操作成功,那么$?的值就会是 0。
  • 如果命令执行出现错误,会返回一个非零的退出状态码。不同的非零值可能代表不同类型的错误,具体的含义因命令而异。例如,命令找不到文件可能返回状态码 1,权限问题可能返回状态码 2 等。
1
2
3
4
5
6
7
8
9
#!/bin/sh
CMD='ls'
eval $CMD # will invoke this cmd via `eval`
echo "status 01 ---$?"

DATECMD="date"
result=$( $DATECMD ) # will invoke ths cmd via `$()` fomatter, NOTE: there are space locate at prefix and suffix.
echo $result
echo $?

上面代码输出:
0
Fri Dec 20 08:30:26 CST 2024
0


Shell中的特殊参数
https://jackiedai.github.io/2024/12/18/007unix_shell/004-Shell之特殊参数/
Author
lingXiao
Posted on
December 18, 2024
Licensed under