Shell 特殊变量

特殊变量

$$

当前 shell 的进程ID

1
$echo $$

输出当前进程的pid

1
2
➜  ~ echo $$
19248
$0 当前脚本的文件名
$n 当前脚本的参数,从1开始 $1第一个参数,$2第二个参数,$n第n个参数
$# 脚本参数的总个数
$* 脚本参数集合,所有的参数被双引号包裹。如果脚本2个参数,$*="$1 $2"
$@ 脚本参数集合,每个参数被单独的双引号包裹。如果脚本2个参数,$*="$1" "$2"
$? 上个命令的返回值。
$$ 当前shell 的进程ID。
$! The process number of the last background command.

示例

1
2
3
4
5
6
7
8
#!/bin/sh

echo "File Name: $0"
echo "First Parameter : $1"
echo "Second Parameter : $2"
echo "Quoted Values: $@"
echo "Quoted Values: $*"
echo "Total Number of Parameters : $#"

输出

1
2
3
4
5
6
7
$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2

$* $@

the $* special parameter takes the entire list as one argument with spaces between and the $@ special parameter takes the entire list and separates it into separate arguments.

1
2
3
4
5
6
#!/bin/sh

for TOKEN in $*
do
echo $TOKEN
done

输出

1
2
3
4
5
6
$./test.sh Zara Ali 10 Years Old
Zara
Ali
10
Years
Old

$?

检查上个命令是否执行成功。

1
2
3
4
➜  ~ pwd
/Users/yxb
➜ ~ echo $?
0

Shell 特殊变量
https://yxibng.github.io/2022/02/25/Shell/2022-02-25-shell 特殊变量/
作者
yxibng
发布于
2022年2月25日
许可协议