2

I have the following code to demonstrate:

#!/bin/bash
function demo() {

   echo "This is A"
   exit 1
   echo "This is B"
}


input=$(demo)
echo "${input}"
echo "This is C"

You can see if I run this script it will print out the following output:

This is A
This is C

Since I have exit 1 function, the script did not terminate and printed the last statement This is C

But when I call the function like this:

#!/bin/bash
function demo() {

   echo "This is A"
   exit 1
   echo "This is B"
}


demo
echo "${input}"
echo "This is C"

Then the program terminated and did not print the last statement "This is C". The output is:

This is A

Is there an explanation for this and how do I force the script to terminate when having the exit 1 there plus assigning the function to a variable like example given. Meaning that, no other statements should be printed after exit 1

5
  • 2
    Btw.: I recommend not to use internal keywords for functions. See type test. Commented Feb 4, 2021 at 11:16
  • 2
    $(...) runs the command in a subshell, and exit just exits from the subshell, not the original script. Commented Feb 4, 2021 at 11:24
  • What's the point of assigning to a variable if you're exiting the script? How can you use the variable? Commented Feb 4, 2021 at 11:25
  • @Barmar In large application, This script needs to exit if the function produced an error with return code 1. So, it shouldn't run other statement and terminate itself when it has error. Example calling API in demo(), something was wrong, so it's useless to assign wrong data to variable. Terminating the script and telling user what is wrong. Commented Feb 4, 2021 at 11:28
  • @Barmar thanks for your explanation about subshell exit. Now I understand why it won't exit. But if there is a way to overcome this, I appreciate your help. Thanks. Commented Feb 4, 2021 at 11:33

1 Answer 1

3

You can check the exit status when assigning the variable, and exit the main script if it failed.

input=$(demo) || exit 1
Sign up to request clarification or add additional context in comments.

1 Comment

Note that if you are using local keyword in a function, you need to define the variable and set its value on separate lines, e.g. local input; input=$(demo) || exit 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.