返回退出code,而不关闭壳 [英] Return an exit code without closing shell

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

问题描述

我想从那个叫另一个脚本中的bash脚本返回退出code,但也可以直接调用。它大致是这样的:

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
# ...

在该行现在退出此处脚本应该退出并返回退出code 1的问题是,

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


  • 我不能使用收益,因为当我忘了,而不是源调用它,回报将的的退出,其余的脚本该脚本将被执行,搞搞。

  • 我不能使用退出,因为这将关闭外壳。

  • 我无法用好的把戏杀-SIGINT $$ ,因为这不允许返回退出code。

  • 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来测试如果脚本是源或所谓的(假,如果​​采购,真要是称呼)和收益退出相应

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.

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

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