1.什么是预设变量
预设变量很像C或者Java的主方法的命令行传参。
| 变量 | 含义 |
|---|---|
| $n | n为数字,$0代表当前执行的进程名,$1-$9代表第一到第九个参数,十以上的参数,十以上的参数需要用大括号包含,如${10} |
| $* | 这个变量代表命令行中所有的参数,$*把所有的参数看成一个整体 |
| $@ | 这个变量也代表命令行中所有的参数,不过$@把每个参数区分对待 |
| $# | 这个变量代表命令行中所有参数的个数 |
| $$ | 这个变量代表命当前进程的进程号 |
| $? | 上一条命令返回的状态,0表示成功,非0表示失败 |
实例: hello.sh
#!/bin/bash
#打印当前进程名字
echo "current pname is \$0=$0"
echo "\$1=$1"
echo "\$2=$2"
echo "\$3=$3"
echo "\$4=$4"
echo "\$5=$5"
echo "\$6=$6"
echo "\$7=$7"
echo "\$8=$8"
echo "\$9=$9"
#打印第十个参数,注意超过10个参数必须使用{}括号。
echo "\$10=${10}"
#打印所有参数
echo "argument number is \$#=$#"
echo "\$@=$@"
echo "\$*=$*"
#打印当前进程编号
echo "current pid is \$\$=$$"
#测试正确的命令
ls
echo "command return status is \$?=$?"
#测试失败的命令,不存在haha文件
ls haha
echo "command return status is \$?=$?"
测试运行
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./hello.sh 1 2 3 4 5 6 7 8 beijing shanghai
current pname is $0=./hello.sh
$1=1
$2=2
$3=3
$4=4
$5=5
$6=6
$7=7
$8=8
$9=beijing
$10=shanghai
argument number is $#=10
$@=1 2 3 4 5 6 7 8 beijing shanghai
$*=1 2 3 4 5 6 7 8 beijing shanghai
current pid is $$=25516
hello.sh
command return status is $?=0
ls: 无法访问haha: 没有那个文件或目录
command return status is $?=2