I have written a simple script
get-consent-to-continue.sh
echo Would you like to continue [y/n]?
read response
if [ "${response}" != 'y' ];
then
exit 1
fi
I have added this script to ~/.bashrc
as an alias
~/.bashrc
alias getConsentToContinue="source ~/.../get-consent-to-continue.sh"
My goal is to be able to call this from another script
~/.../do-stuff.sh
#!/usr/bin/env bash
# do stuff
getConsentToContinue
# do other stuff IF given consent, ELSE stop execution without closing terminal
Goal
I want to be able to
bash ~/.../do-stuff.sh
And then, when getConsentToContinue
is called, if I respond with anything != 'y'
, then do-stuff.sh
stops running without closing the terminal window.
The Problem
When I run
bash ~/.../do-stuff.sh
the alias is not accessible.
When I run
source ~/.../do-stuff.sh
Then the whole terminal closes when I respond with 'n'.
I just want to cleanly reuse this getConsentToContinue
script to short-circuit execution of whatever script happens to be calling it. It's just for personal use when automating repetitive tasks.
Thanks in advance!
CodePudding user response:
A script can't force its parent script to exit, unless you source
the script (since it's then executing in the same shell process).
Use an if
statement to test how getConsentToContinue
exited.
if ! getConsentToContinue
then
exit 1
fi
or more compactly
getConsentToContinue || exit