如何在 Bash 中抛出错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34096777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:00:12  来源:igfitidea点击:

How to throw an error in Bash?

bash

提问by boop

How do I throw an error in bash to get in my catchclause (I'm not sure what this expression is actually called)

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

{
  # ...
  if [ "$status" -ne "200" ]
    # throw error
  fi
} || {
  # on error / where I want to get if status != 200
}

I know I just could use a function but this case made me curious if it would be possible to do this

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

采纳答案by Chris Maes

There are multiple ways to do something similar:

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

use subshells(might not be the best solution if you want to set parameters etc...)

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

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

use an intermediate errorvariable(you can catch multiple errors by setting different numbers. Also: less indentation depth)

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

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

if [ $error != 0 ]
then
    echo "error $error thrown"
fi

use immediately the exit value of your test(note that I changed -neto -eq)

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

[[ "$status" -eq "200" ]] || echo "error thrown"

回答by toth

One way to do it is with just exit as shellter mentions, but you have to create a subshell for that work (which exists on the exit). To do this, replace the curly brackets with parentheses.

一种方法是像 shellter 提到的那样直接退出,但您必须为该工作创建一个子 shell(它存在于出口上)。为此,请用括号替换大括号。

The code will be

代码将是

(
 # ...
 if [ "$status" -ne "200" ]
    exit 1
 fi
) || {
   # on error / where I want to get if status != 200
}

回答by John1024

The return code for the braces is the return code of the last statement executed in the braces. So, here is one method that uses the shell-builtin false:

大括号的返回码是大括号中执行的最后一条语句的返回码。所以,这是一种使用 shell-builtin 的方法false

{
  # ...
  if [ "$status" -ne "200" ]; then
    false # throws "error" (return code=1)
  fi
} || {
  echo "Caught error" # on error / where I want to get if status != 200
}

In this particular case, the ifstatement is superfluous. The test statement, [ "$status" -ne "200" ], throws the exit code that you need:

在这种特殊情况下,该if语句是多余的。测试语句 ,[ "$status" -ne "200" ]抛出您需要的退出代码:

{
  # ...
  ! [ "$status" -ne "200" ]
} || {
  echo "Caught error" # on error / where I want to get if status != 200
}