Linux几个变量

linux shell中部分变量的含义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$0:脚本名

$1:传给脚本的第一个参数

$2:传给脚本的第二个参数

$$:脚本运行的PID

$@:传给脚本的所有参数列表(list形式)

$*:传给脚本的所有参数列表(字符串形式)

$#:传给脚本的参数个数

$?:上个已执行命令的退出状态码,成功为0

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash
# test linux variables
# 20181224 by kyle

# 使用basename获取脚本名,避免输出脚本名时候带上命令:./test1.sh
name=$(basename $0)

echo
echo "number of variables is:$#"
echo "the first variable is: $1"
echo "the second is: $2"
echo "the scrip's name is: $name"
echo "the script's PID is: $$"
echo "the parameters are: $@"
echo "the parameter list is: $*"
echo "show script stat: $?"
echo

执行结果:

1
2
3
4
5
6
7
8
9
10
[root@localhost mountTest]# ./VariablesTest.sh 

number of variables is:0
the first variable is:
the second is:
the scrip's name is: VariablesTest.sh
the script's PID is: 4829
the parameters are:
the parameter list is:
show script stat: 0

*比较“$@”和“$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/bin/bash
# compare $@ with $*
# 20181224 by kyle

echo
echo "followed by \$*"
count=1
#
for param in "$*"
do
echo "\$* Parameter #$count = $param"
count=$[ $count + 1 ]
done
#

echo
echo "Here is \$@"
count=1
#

for param in "$@"
do
echo "\$@ Parameter #$count = $param"
count=$[ $count + 1 ]
done

执行结果:

1
2
3
4
5
6
7
8
9
10
11
[root@localhost mountTest]# ./ShellTest.sh 1 2 3 4 5 

followed by $*
$* Parameter #1 = 1 2 3 4 5

Here is $@
$@ Parameter #1 = 1
$@ Parameter #2 = 2
$@ Parameter #3 = 3
$@ Parameter #4 = 4
$@ Parameter #5 = 5
文章目录
|