Let's say I have a script which is executable. It looks like this:
if true
then
echo "started if statement"
exit
fi
echo "hello"
When I run this script, hello is not printed, because exit
exits the entire shell. Is there a way to make exit
(or some other statement) simply exit the if statement?
Best How To :
First: Don't do any of this. Structure your program some other way. If you described to us why you think you need this behavior, we could potentially have told you how to achieve it otherwise.
Getting down to the question: If you wrap your block in a loop, you can use break
to exit early:
for _ in once; do
if true; then
echo "in the loop"
break
echo "not reached"
fi
done
echo "this is reached"
Alternately, you can use a function, and return
to exit early:
myfunc() {
if true; then
echo "in the loop"
return
fi
echo "unreached"
}
myfunc
echo "this is reached"
Alternately, you can wrap your loop in a subshell (though this will prevent it from doing other things, like variable assignments that impact code outside the subshell, as well):
(if true; then
echo "in the block"
exit
echo "unreached"
fi)
echo "this is reached."