不要中断 bash 脚本中设置了 -e 标志的代码

问题描述 投票:0回答:1

我得到了代码

#!/bin/bash
set -e
helm status deployment-name
if [ $? -eq 0 ]; then
  echo "uninstall helm release"
  helm uninstall deployment-name
else 
  echo "helm reease doesnot exist"
fi

头盔安装....

所以脚本检查 helm release 是否存在,如果存在我们得到 0,如果不存在错误 但如果不存在,则应通过 If 并打印 echo“helm reease 不存在”,但我们有一个标志设置 -e 导致退出/中断脚本。 如果发生错误,我应该如何实现它,它将转到 else 而不是退出代码。 头盔版本 3.10

bash helm3
1个回答
0
投票

请阅读https://mywiki.wooledge.org/BashFAQ/105 虽然近年来,设置

errexit
已变得流行,但这样做是错误的。显式优于隐式,
cmd || exit
优于
set -e; cmd

运行命令后无需显式检查

$?
的值。当
errexit
禁用时,
if cmd; then ...
相当于
cmd; if [ $? = 0 ] then ...
。当
errexit
启用时,
if cmd; then ...
cmd || : ; if [ $? = 0 ]; then ...
相同。在这两种情况下,首选前者。

换句话说,你有几个选择。您可以通过编写简单地禁用 errexit:

 set +e 
 helm status "$deployment_name"
 ...

(或者只是删除

set -e
,IMO 是正确的做法,但您可能需要对脚本的其余部分进行适当的更改),或者您可以这样做:

if helm status "$deployment_name"; then ...

或:

helm status "$deployment_name" || :
if [ $? = 0 ]; then ...

IMO,最好的解决方案是删除

set -e
并根据需要编辑脚本的其余部分。朋友不要让朋友启用errexit。最后给出最坏的可能解决方案;您永远不应该显式检查
$?
的值,除非可能在
case
语句中,其中进程针对不同的错误状态返回多个非零值。

© www.soinside.com 2019 - 2024. All rights reserved.