当前位置:   article > 正文

得到command的退出状态_退出command

退出command

shell脚本执行的每个命令都会有退出状态,退出状态是一个数值,0表示命令执行成功,非0表示命令执行失败。
通过$?得到上一个执行命令的退出状态。

date
echo $?
date-foo-bar
printf '%d\n' $?
  • 1
  • 2
  • 3
  • 4

得到命令的退出状态

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"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
#!/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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/189275
推荐阅读
相关标签
  

闽ICP备14008679号