I want to run the command mvn clean in a bash script. But I want to put it in an if statement. If the clean does not run properly I would like to exit out of the bash script wit
Here's what you want:
mvn clean
if [ "$?" -ne 0 ]; then
echo "Maven Clean Unsuccessful!"
exit 1
fi
Explanation:
$?
is a special shell variable that contains the exit code (whether it terminated successfully, or not) of the most immediate recently executed command.-ne
is an option to the test
builtin [
. It stands for "not equal". So here we are testing if the exit code from mvn clean
is not equal to zero.echo "Maven Clean Unsucccessful!"
- If this is the case, then we output some indicative message, and exit the script itself with an errant exit code.When you do $(mvn clean)
, that instead spawns a new subshell to run mvn clean
, then simply dumps everything that was output to stdout
in that subshell from running mvn clean
to where $(...)
was used in the parent shell.
Alternatively, you can do:
mvn clean || { echo "Maven Clean Unsuccessful"; exit 1; }
Which is just shorthand syntactic sugar for doing the same thing.