Rewriting this question to avoid more downvotes, since it's too late for me to delete it:
I'm writing a script that asks a user for confirmation and before sourcing some other scripts. To simplify the code, imagine that there are two scripts which might be sourced, but I want the user to either source none or exactly one of the scripts - not both. I was trying to use a statement of the form if true source-script else exit which wasn't working because I'd exit the if statement, but also the script as a whole, and wouldn't have a chance to do necessary cleanup. Originally, my script looked something like this:
echo "This script might do something terrible to your computer."
read -p "Do you wish to continue? (y/[n]) " -n 1;
echo
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
source "terrible_script.sh"
# want some way to ensure that we don't prompt the user about the next script
# don't want to just exit if the response is 'n' because we have to do cleanup
fi
echo "This script might do something really good to your computer."
read -p "Do you wish to continue? (y/[n]) " -n 1;
echo
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
source "good_script.sh"
fi
# do cleanup here
# regardless of whether or not any scripts were sourced
@charles-duffy provided the answer - simply wrap the prompts in a function. Something like:
function badscript() {
echo "This script might do something terrible to your computer."
read -p "Do you wish to continue? (y/[n]) " -n 1;
echo
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
source "terrible_script.sh"
return 0
fi
}
function goodscript() {
echo "This script might do something really good to your computer."
read -p "Do you wish to continue? (y/[n]) " -n 1;
echo
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
source "good_script.sh"
fi
}
if ! badscript
then
goodscript
fi
# cleanup code here
exitis defined as exiting the shell. That's what it's defined to do. Why would you expect it to ever be capable of doing anything different?breakcommand to perform an early exit from loops, but you can't use that to break out of anifwithout wrapping it inside a loop.returnworks insideif-statements