如何在 Bash 中抛出错误?

boo*_*oop 7 bash

如何在 bash 中抛出错误以进入我的catch子句(我不确定这个表达式实际上叫什么)

{
  # ...
  if [ "$status" -ne "200" ]
    # throw error
  fi
} || {
  # on error / where I want to get if status != 200
}
Run Code Online (Sandbox Code Playgroud)

我知道我只能使用一个函数,但这个例子让我很好奇是否可以做到这一点

Chr*_*aes 3

有多种方法可以做类似的事情:

使用子shell(如果您想设置参数等,可能不是最好的解决方案...)

(
if [[ "$status" -ne "200" ]]
then
    exit 1
fi 
) || (
  # on error / where I want to get if status != 200
  echo "error thrown"
)
Run Code Online (Sandbox Code Playgroud)

使用中间错误变量(您可以通过设置不同的数字来捕获多个错误。另外:减少缩进深度)

if [[ "$status" -ne "200" ]]
then
    error=1
fi

if [ $error != 0 ]
then
    echo "error $error thrown"
fi
Run Code Online (Sandbox Code Playgroud)

立即使用测试的退出值(请注意,我更改-ne-eq

[[ "$status" -eq "200" ]] || echo "error thrown"
Run Code Online (Sandbox Code Playgroud)