为什么部署sh脚本不会失败nginx重新加载失败?

我有sh脚本重新启动nginx,如下所示:

#!/bin/sh -e set -e error_exit() { d=$(date '+%D %T :: ') echo "$d Error: $*" >&2 exit 1 } if ! sudo service nginx reload then # Exit with error error_exit "Could not reload nginx" fi echo "Deployment Done!" 

但我的问题是脚本继续执行事件,如Reloading nginx configuration nginx [fail]并达到Deployment Done! 回声。 似乎情况总是true

那么,如果nginx重装失败,我怎么能停止执行bash脚本呢?

通过returnreplaceexit 1 ,并在exit 1之前插入一行。

更新:

用GNU grep试试这个:

 #!/bin/sh -e set -e error_exit() { d=$(date '+%D %T :: ') echo "$d Error: $*" >&2 exit 1 } out="$(sudo service nginx reload 2>&1 | grep -o fail || true)" # new if [ "x$out" = "xfail" ] # modified then # Exit with error error_exit "Could not reload nginx" fi echo "Deployment Done!"