在不关闭 shell 的情况下返回退出代码 [英] Return an exit code without closing shell

查看:15
本文介绍了在不关闭 shell 的情况下返回退出代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从在另一个脚本中调用的 BASH 脚本返回退出代码,但也可以直接调用.大致是这样的:

I'd like to return an exit code from a BASH script that is called within another script, but could also be called directly. It roughly looks like this:

#!/bin/bash
dq2-get $1
if [ $? -ne 0 ]; then
  echo "ERROR: ..."
  # EXIT HERE
fi
# extract, do some stuff
# ...

现在在 EXIT HERE 行中,脚本应该退出并返回退出代码 1.问题是

Now in the line EXIT HERE the script should exit and return exit code 1. The problem is that

  • 我不能使用 return,因为当我忘记 source 脚本而不是调用它时,return 将 not 退出,并且脚本的其余部分将被执行并把事情搞砸了.
  • 我不能使用 exit,因为这会关闭 shell.
  • 我不能使用巧妙的技巧 kill -SIGINT $$,因为这不允许返回退出代码.
  • I cannot use return, because when I forget to source the script instead of calling it, return will not exit, and the rest of the script will be executed and mess things up.
  • I cannot use exit, because this closes the shell.
  • I cannot use the nice trick kill -SIGINT $$, because this doesn't allow to return an exit code.

有没有我忽略的可行替代方案?

Is there any viable alternative that I have overlooked?

推荐答案

你可以使用 x"${BASH_SOURCE[0]}" == x"$0" 来测试脚本是否有源或调用(如果来源为 false,如果调用则为 true)并相应地 returnexit.

You can use x"${BASH_SOURCE[0]}" == x"$0" to test if the script was sourced or called (false if sourced, true if called) and return or exit accordingly.

这篇关于在不关闭 shell 的情况下返回退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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