如何使bash函数在出现任何错误时返回1 [英] How to make a bash function return 1 on any error

查看:57
本文介绍了如何使bash函数在出现任何错误时返回1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个虚假的bash函数,例如:

I have a fake bash function such as this:

has_error() {
  true
  echo "Ok..."
  false
  echo "Shouldn't be here!"
}

运行此功能并检查错误状态时,我希望发生的事情:

What I'd like to have happen when I run this function and check the error status:

> has_error; echo $?
Ok...
1

但是实际上会发生什么:

But what actually happens:

> has_error; echo $?
Ok...
Shouldn't be here!
0

问题是函数在引发错误后继续执行,而且,我什至无法检测到引发了错误.我该如何更改?我可以在函数的开头放置一个 set -e ,但是如果抛出错误,我的整个外壳将终止.我想要的是简单地使其返回并将退出状态设置为1.我可以通过在命令之间放置&& 或在每行后缀||返回1 ,但是它们都不是很优雅.正确的方法是什么?

The problem is that the function keeps executing after an error has been thrown, and moreover, I can't even detect that an error was thrown. How can I change this? I could put a set -e at the beginning of the function, but then my whole shell will terminate if an error gets thrown. What I'd like is to simply have it return and set the exit status to 1. I could do it with putting && in between the commands, or by suffixing every line with || return 1, but neither of those are very elegant. What's the proper way to do this?

似乎我还不够清楚,因为很多答复似乎表明我实际上并不知道如何在bash中执行测试.如上所述,我知道我可以手动测试函数中的每个命令,并根据需要返回或处理错误.我也知道我可以 set -e 并导致我的shell会话因错误而终止.但是我要问的是:是否有一种方法可以让函数停止继续执行-如果没有显式测试-该函数中的任何命令是否返回非零状态?

It seems that I'm not being clear enough, because a lot of the responses seem to suggest that I don't actually know how to perform tests in bash. As I mention above, I am aware that I could manually test each command in my function, and return or handle errors as I wanted. I'm also aware that I can set -e and cause my shell session to terminate on an error. But what I'm asking is: is there a way to have a function cease to continue execution -- without an explicit test -- if any of the commands within that function return nonzero statuses?

推荐答案

如果您的函数不需要设置任何全局变量,则可以让该函数创建一个子外壳,其中 set -e 用来.子外壳将退出,而不是调用 has_error 的外壳.

If your function doesn't need to set any global variables, you can have the function create a subshell in which set -e is used. The subshell will exit, not the shell in which has_error is called.

has_error () (    # "(", not "{"
  set -e
  true
  echo "Ok..."
  false
  echo "Shouldn't be here!"
)

这篇关于如何使bash函数在出现任何错误时返回1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆