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 with an echo statement. Here is the code that is causing the problem: if [ mvn clean ]; then
I tried putting $(mvn clean) inside the if statement but there were too many arguments says the terminal. Does anyone know if this is possible? Thanks!
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.
No parentheses needed for checking the exit status:
if mvn clean ; then
echo ok
else
echo Something went wrong.
exit 1
fi
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