Return an exit code without closing shell
Asked Answered
J

6

40

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

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

  • 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?

Jehoshaphat answered 24/5, 2011 at 15:1 Comment(4)
Don't forget to source the script is my advice.Exhume
Software should always be written in a way that misuse cannot lead to problems.Jehoshaphat
I disagree with Neils advice. Instead, do not ever source the script but always call it.Zucchetto
Check the value of $SHLVL and conditionally exit or not.Gourmandise
W
8

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.

Whitewing answered 24/5, 2011 at 15:7 Comment(4)
I tried that, but I got bored, because I couldn't put that into a function (because then again I'd miss a way to exit) -- I'd have to place an if construction at every place in the script where an error could occur. Or is there a better way?Jehoshaphat
You could have the if statement be part of a signal trap and then replace every EXIT HERE with a kill -SIGWHATEVER $$Whitewing
The xs are 100% unnecessary; they add nothing whatsoever over the behavior of [ "${BASH_SOURCE[0]}" = "$0" ]. The only time there's ever a value to the x$foo idiom in shells that comply with the POSIX.2 standard (ever since its initial early-90s publication) is when you're using test calls with more than three arguments (which the aformentioned standard explicitly flags as obsolescent). And if you need compatibility with ancient shells, == is flatly wrong on its face; the only backwards-compatible (or even baseline POSIX-compliant) string comparison operator is =.Carriole
Beyond that, this isn't a reliable test; $0 can be modified by callers using exec -a name.Carriole
R
25

The answer to the question title (not in the body as other answers have addressed) is:

Return an exit code without closing shell

(exit 33)

If you need to have -e active and still avoid exiting the shell with a non-zero exit code, then do:

(exit 33) && true

The true command is never executed but is used to build a compound command that is not exited by the -e shell flag.

That sets the exit code without exiting the shell (nor a sourced script).

For the more complex question of exiting (with an specific exit code) either if executed or sourced:

#!/bin/bash
[ "$BASH_SOURCE" == "$0" ] &&
    echo "This file is meant to be sourced, not executed" && 
        exit 30

return 88

Will set an exit code of 30 (with an error message) if executed.
And an exit code of 88 if sourced. Will exit both the execution or the sourcing without affecting the calling shell.

Ralina answered 23/11, 2018 at 23:58 Comment(3)
(exit 33) Fantastic!!Stink
This is tremendously useful. one thing I have had trouble with this though is I like to use 'set -e' to halt a script in its tracks. unfortunately return 88 will cause this to kill the shell as before. Are there any pointers on being able to handle that case?Soso
@Soso The usual solution to keep the shell working even if the -e option is set is to make the command line a compound command, the simplest compound command is (exit 33) && true. The true command is never actually executed.Ralina
C
12

Use this instead of exit or return:

[ $PS1 ] && return || exit;

Works whether sourced or not.

Cookie answered 24/1, 2014 at 23:3 Comment(3)
If use single bracket [ ] instead double [[ ]], it will work with sh also.Lecturer
It did not work for me as written (running as script did not work), but the following works: [ -v PS1 ] && return || exit. A way to test it easily: [ -v PS1 ] && (echo returning; return) || (echo exiting; exit)Hankhanke
Also, if I understand it correctly, this solution does NOT work when source-ing from inside another script. The accepted answer works in that (complex) scenario though.Hankhanke
W
8

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.

Whitewing answered 24/5, 2011 at 15:7 Comment(4)
I tried that, but I got bored, because I couldn't put that into a function (because then again I'd miss a way to exit) -- I'd have to place an if construction at every place in the script where an error could occur. Or is there a better way?Jehoshaphat
You could have the if statement be part of a signal trap and then replace every EXIT HERE with a kill -SIGWHATEVER $$Whitewing
The xs are 100% unnecessary; they add nothing whatsoever over the behavior of [ "${BASH_SOURCE[0]}" = "$0" ]. The only time there's ever a value to the x$foo idiom in shells that comply with the POSIX.2 standard (ever since its initial early-90s publication) is when you're using test calls with more than three arguments (which the aformentioned standard explicitly flags as obsolescent). And if you need compatibility with ancient shells, == is flatly wrong on its face; the only backwards-compatible (or even baseline POSIX-compliant) string comparison operator is =.Carriole
Beyond that, this isn't a reliable test; $0 can be modified by callers using exec -a name.Carriole
H
2

Another option is to use a function and put the return values in that and then simply either source the script (source processStatus.sh) or call the script (./processStatus.sh) . For example consider the processStatus.sh script that needs to return a value to the stopProcess.sh script but also needs to be called separately from say the command line without using source (only relevant parts included) Eg:

check_process ()
{
  if [ "$1" -eq "50" ]
  then
    return 1       
  else
    return 0
  fi       
}

and

source processStatus.sh $1
RET_VALUE=$?
if [ "$RET_VALUE" -ne "0" ]
then
  exit 0
fi
Hsiuhsu answered 2/1, 2015 at 9:18 Comment(1)
50 doesn't need quotes around it, because it parses to the same two-character string either way. $1 does need quotes, because it can parse to zero strings, or one string, or more than one string depending on its contents. Consider check_process "1 -eq 1 -o 39"; when you don't have the quotes that runs if [ 1 -eq 1 -o 39 -eq 50 ], which is true, whereas [ "1 -eq 1 -o 39" -eq 50 ] would correctly be an error.Carriole
C
0

You can use return if you use set -e in the beginning of the script.

If you just want to check if the function returned no errors, I'd rather suggest rewriting your code like this:

#!/bin/bash

set -e # exit program if encountered errors

dq2-get ()
{
  # define the function here
  # ...
  if [ $1 -eq 0 ]
  then
    return 0
  else
    return 255
  # Note that nothing will execute from this point on,
  # because `return` terminates the function.
}

# ...
# lots of code ...
# ...

# Now, the test:
# This won't exit the program.
if $(dq2-get $1); then
  echo "No errors, everything's fine"
else
  echo "ERROR: ..."
fi
# These commands execute anyway, no matter what
# `dq2-get $1` returns (i.e. {0..255}).
# extract, do some stuff
# ...

Now, the code above won't leave the program if the function dq2-get $1 returns errors. But, implementing the function all by itself will exit the program because of the set -e. The code below describes this situation:

# The function below will stop the program and exit
# if it returns anything other than `0`
# since `set -e` means stop if encountered any errors.
$(dq2-get $1)
# These commands execute ONLY if `dq2-get $1` returns `0`
# extract, do some stuff
# ...
Cimbura answered 24/4, 2020 at 7:51 Comment(1)
if $(some-function some-arg); then is a really bad idea, because if some-function writes anything to stdout that stdout will be executed as a command and the exit status of the command will be used for the if instead of the exit status of some-function. Instead, use if some-function some-arg; thenCarriole
L
0

Thanks for the question, my case was to source a file for some setup, but end the script and skip the setup actions if certain conditions were not met.

I had hit the issue of an attempt to use exit() actually causing the closing of my terminal, and found myself here :D

After reviewing the options for the specific solution i just went with something like the below, I also think Deepaks answer is worth reviewing if this approach works in your case.

if [ -z "$REQUIRED_VAR" ]; then
  echo "please check/set \$REQUIRED_VAR ..."
  echo "skipping logic"
else
  echo "starting logic"
  doStuff()
  echo "completed logic"
fi
Leath answered 29/7, 2022 at 11:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.