When writing bash that sources another file, sometimes I want to skip processing if some conditions are true. For now, I've been either:
Both of these strategies have some drawbacks. It'd be so much better if I could write my scripts with this code style:
main.sh
echo "before"
. other
echo "after"
other.sh
# guard
if true; then
# !! return to main somehow
fi
if true; then
# !! return to main somehow
fi
# commands
echo "should never get here"
Is there a way to do this so that the echo "after"
line in main gets called?
Yes, you could return
:
if true; then
return
fi
Quoting help return
:
return: return [n]
Return from a shell function.
Causes a function or sourced script to exit with the return value specified by N. If N is omitted, the return status is that of the last command executed within the function or script.
Exit Status: Returns N, or failure if the shell is not executing a function or script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With