赞
踩
shell脚本执行的每个命令都会有退出状态,退出状态是一个数值,0表示命令执行成功,非0表示命令执行失败。
通过$?得到上一个执行命令的退出状态。
date
echo $?
date-foo-bar
printf '%d\n' $?
得到命令的退出状态
command
status=$?
## run date command ##
cmd="date"
$cmd
## get status ##
status=$?
## take some decision ##
[ $status -eq 0 ] && echo "$cmd command was successful" || echo "$cmd failed"
#!/bin/bash # # Sample shell script to demo exit code usage # # set -e ## find ip in the file ## grep -q 192.168.2.254 /etc/resolv.conf ## Did we found IP address? Use exit status of the grep command ## if [ $? -eq 0 ] then echo "Success: I found IP address in file." exit 0 else echo "Failure: I did not found IP address in file. Script failed" >&2 exit 1 fi
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。