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
You can check the exit status when assigning the variable, and exit the main script if it failed.
input=$(demo) || exit 1