Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvn in bash script if statement

Tags:

bash

maven

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!

like image 574
grivera Avatar asked Nov 30 '12 19:11

grivera


2 Answers

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.

like image 155
sampson-chen Avatar answered Sep 18 '22 13:09

sampson-chen


No parentheses needed for checking the exit status:

if mvn clean ; then
   echo ok
else
   echo Something went wrong.
   exit 1
fi
like image 38
choroba Avatar answered Sep 20 '22 13:09

choroba