bash - 如何在 Bash 中抛出错误?

标签 bash

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

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

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

最佳答案

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

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

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

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

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

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

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

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

关于bash - 如何在 Bash 中抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34096777/

相关文章:

php - 有选择地使用 Sed 替换 SQL 语法

bash - 如何并排输出sed?

bash 脚本 : commands after the loop are not executed if the loop condition is false

linux - 获取语​​法错误 : "fi" unexpected (expecting "then") in shell scripts

bash - 如何在 Bash 的 if 语句中使用带参数的函数?

python - 如何通过shell脚本编辑XML文件来更改所有数字,其中原始点除以1.3?

linux - 使用 linux 命令 top 提取总 HD 内存和 HD 内存使用情况

linux - 在 Bash 脚本中使用 Curl 检查网站是否正常运行

linux - cat pipe awk 操作与文件上 awk 命令的比较

bash - 如何从命令行使用 ffmpeg 进行批量转换