特殊状态变量
$? 上一次命令执行状态返回值,0正确,非0失败
$$ 当前脚本的进程号
$! 上一次后台进程的PID
$_ 上一次命令的最后一个参数
查找方式 man bash
搜索Specail Parameters
脚本控制返回值
[ $# -ne 2 ] && {
echo "must be two args"
exit 119
}
echo ok
运行结果:
xiao123@xiao123:~/Downloads$ cat ./t1.sh
[ $# -ne 2 ] && {
echo "must be two args"
exit 119
}
echo ok
xiao123@xiao123:~/Downloads$ bash ./t1.sh 11
must be two args
xiao123@xiao123:~/Downloads$ echo $?
119
xiao123@xiao123:~/Downloads$ bash ./t1.sh 11 22
ok
xiao123@xiao123:~/Downloads$ echo $?
0
xiao123@xiao123:~/Downloads$
获取上一次后台程序进程PID $!
xiao123@xiao123:~/Downloads$ nohup ping baidu.com & 1>/dev/null
[1] 8458
xiao123@xiao123:~/Downloads$ nohup: ignoring input and appending output to 'nohup.out'
xiao123@xiao123:~/Downloads$ ps -ef | grep ping
xiao123 1680 1328 0 2月22 ? 00:00:11 /usr/libexec/gsd-housekeeping
xiao123 8458 6005 0 10:22 pts/1 00:00:00 ping baidu.com
xiao123 8460 6005 0 10:23 pts/1 00:00:00 grep --color=auto ping
xiao123@xiao123:~/Downloads$ echo $!
8458
xiao123@xiao123:~/Downloads$
获取当前脚本的PID $$
xiao123@xiao123:~/Downloads$ cat ./t1.sh
[ $# -ne 2 ] && {
echo "must be two args"
exit 119
}
echo ok
echo "当前脚本的PID:$$"
xiao123@xiao123:~/Downloads$ bash ./t1.sh 11 22
ok
当前脚本的PID:8491
xiao123@xiao123:~/Downloads$ bash ./t1.sh 11 22
ok
当前脚本的PID:8492
xiao123@xiao123:~/Downloads$ bash ./t1.sh 11 22
ok
当前脚本的PID:8493
xiao123@xiao123:~/Downloads$ bash ./t1.sh 11 22
ok
当前脚本的PID:8494
xiao123@xiao123:~/Downloads$
获取上次命令的最后一个参数
xiao123@xiao123:~/Downloads$ bash ./t1.sh 11 22
ok
当前脚本的PID:8498
xiao123@xiao123:~/Downloads$ echo $_
22
xiao123@xiao123:~/Downloads$