I try to make a function which can interrupt the script execution (due to fatal error):
quit() {
echo -e "[ERROR]" | log
exit 1
}
Call example:
if [ "$#" -eq 1 ]; then
# Do stuff
else
echo -e "function getValue: wrong parameters" | log
quit
fi
Function quit is called (echo in the logfile) but the script keeps going. I've read that exit only terminate the subshell (is that true?) which means that it terminates the quit function but not the entire script.
For now, I prefer not use return code in quit method as it implies a lot of code refactoring.
Is there a way to stop the script from the quit function?
EDIT: full example of a case where the error appears:
#!/bin/bash
logfile="./testQuit_log"
quit() {
echo "quit" | log
exit 1
}
log() {
read data
echo -e "$data" | tee -a "$logfile"
}
foo() {
if [ "$#" -ne 1 ]; then
echo "foo error" | log
quit
fi
echo "res"
}
rm $logfile
var=`foo p1 p2`
var2=`foo p1`
echo "never echo that!" | log
EDIT2: it works correctly when I switch these lines:
var=`foo p1 p2`
var2=`foo p1`
with
var= foo p1 p2
var2= foo p1
Any explanation? Is that because of the subshell?
exitwill exit the script. The function is not a script. That should work as written. Can you write a short but complete sample that fails to work in the way you are seeing?-eon all the echos? It's non-portable and does nothing in both the cases you show. (printfwill interpret C escape sequences in its format string, and is portable. Just remember that unlike echo it does not automatically add a\n, so you have to add that to the format if you want it.)`), and that creates a subshell, so the parent doesn't exit. I don't know a good workaround, if you need to keep the output in a variable. Regarding why edit2 works, you forgot the backticks. Your variable should remain unset.kill "$PPID"before the exit. This is a little hacky though. You'd have to make sure you only callfoo()in a subshell.