1 $0, $1, $2,…, $n
$0
:这个特殊一点表示命令本身;$1
: 表示第一个参数;$2
:表示第二个参数;$n
:表示第n个参数;
[root@localhost shell]# cat script.sh
echo $0
echo $1
echo $2
[root@localhost shell]# ./script.sh Hello World
./script.sh
Hello
World
注意: 由于历史原因, $n只能针对10以内的数字,大于等于10需要用括号将数值包括起来
[jiangjian@localhost shell]$ cat echoArguments.sh
#! /bin/bash
echo $1
echo $9
echo $10
echo ${10}
[jiangjian@localhost shell]$ ./echoArguments.sh 1 2 3 4 5 6 7 8 9 a b
1
9
10
a
[jiangjian@localhost shell]$
2 $#
$#
:表示实际的参数个数;
[root@localhost shell]# cat arguments-length.sh
echo "length is " $#
[root@localhost shell]# ./arguments-length.sh 1 2 3 4 5 6
length is 6
3 $$
$$
:表示当前进程的pid;
[root@localhost shell]# cat output-pid.sh
echo "my pid is " $$
[root@localhost shell]# ./output-pid.sh
my pid is 47282
[root@localhost shell]# echo $$
46946
[root@localhost shell]#
4 $?
$?
:表示上一个命令执行的退出状态
[root@localhost shell]# cat error.sh
exit 66
[root@localhost shell]# ./error.sh
[root@localhost shell]# echo $?
66
[root@localhost shell]#
5 $!
$!
:表示最近一个后台执行程序的pid;
[root@localhost shell]# sleep 60 &
[1] 47395
[root@localhost shell]# sleep 70 &
[2] 47396
[root@localhost shell]# echo $!
47396
[root@localhost shell]#
6 $* 和 $@的区别
$*
: Stores all the arguments that were entered on the
command line ($1 $2 …).
"$@"
: Stores all the arguments that were entered
on the command line, individually quoted ("$1" “$2” …).
[root@localhost shell]# cat arguments.sh
#!/bin/bash
echo "Using \"\$*\":"
for a in "$*"; do
echo $a;
done
echo -e "\nUsing \$*:"
for a in $*; do
echo $a;
done
echo -e "\nUsing \"\$@\":"
for a in "$@"; do
echo $a;
done
echo -e "\nUsing \$@:"
for a in $@; do
echo $a;
done
[root@localhost shell]# ./arguments.sh one two "three four"
Using "$*":
one two three four
Using $*:
one
two
three
four
Using "$@":
one
two
three four
Using $@:
one
two
three
four
[root@localhost shell]#