linux shell变量$#,$@,$0,$1,$2的含义解释

时间:2021-09-15 15:38:36

变量说明: 
$$ Shell本身的PID(ProcessID) 
$! Shell最后运行的后台Process的PID 
$? 最后运行的命令的结束代码(返回值) 
$- 使用Set命令设定的Flag一览 
$* 所有参数列表。 所有的参数被认为是一个字符串
$@ 所有参数列表。参数是独立的字符串
$# 添加到Shell的参数个数 
$0 Shell本身的文件名 
$1~$n 添加到Shell的各参数值。$1是第1个参数、$2是第2个参数…。 

通过一个脚本,来看看各个变量的效果

 1 #!/bin/sh
2
3 ## RustFisher
4
5 echo "----------------------"
6 echo "PID: \$$ $$"
7 echo "option numbers: \$# $#"
8 echo "last return: \$? $?"
9 echo "all parameters: \$* $*"
10 echo "all parameters: \$@ $@"
11 echo "file name: \$0 $0"
12 echo "1st param: \$1 $1"
13 echo "2nd param: \$2 $2"
14 echo "3rd param: \$3 $3"
15 echo "4th param: \$4 $4"
16 echo "9th parem: \$9 $9"
17 echo "-----------------------"
18
19 index=1
20
21 echo "get args by \"\$@\":"
22
23 for arg in "$@"
24 do
25 echo "Arg #$index=$arg"
26 let "index+=1"
27 done
28
29 echo "-----------------------"
30
31 index=1
32
33 echo "get args by \"\$*\":"
34
35 for arg in "$*"
36 do
37 echo "Arg #$index=$arg"
38 done
39
40 echo "-----------------------"

输出结果:

$ sh show.sh dont "worry be" happy
----------------------
PID: $$
12897
option numbers: $#
3
last return: $? 0
all parameters: $
* dont worry be happy
all parameters: $@ dont worry be happy
file name: $0 show.sh
1st param: $
1 dont
2nd param: $
2 worry be
3rd param: $
3 happy
4th param: $
4
9th parem: $
9
-----------------------
get args by
"$@":
Arg #
1=dont
Arg #
2=worry be
Arg #
3=happy
-----------------------
get args by
"$*":
Arg #
1=dont worry be happy
-----------------------