mvn not found when executed via Jenkins shell script

Viewed 2887

I have set M2_HOME under Manage Jenkins -> configure system -> Environment variables and also under Manage Jenkins -> global tool configuration.

When I use maven project, it is working fine.
But when I use freestyle project and execute shell, it throws an error "mvn not found".

But when I give echo $M2_HOME in Execute shell, it shows the correct path.
Also, when I tried $M2_HOME/mvn compile, it worked fine.
I could not figure out the exact issue.

Error [Compile]

$ /bin/sh -xe /tmp/jenkins1984982949384007169.sh

+ mvn --version

/tmp/jenkins1984982949384007169.sh: 2: /tmp/jenkins1984982949384007169.sh: mvn: not found

Build step 'Execute shell' marked build as failure

Finished: FAILURE
1 Answers

The shell which executes the mvn command doesn't know that the path for the script in in the M2_HOME variable. The shell will only look at commands listed in the $PATH variable.

So there are two solutions:

  • Always use "$M2_HOME/mvn" to execute Maven (or rather "$M2_HOME/bin/mvn" since M2_HOME should point to the folder which contains bin and lib and not to the script itself).

  • Change the path at the top of the script to make the shell search in the right place:

    export PATH="$M2_HOME/bin:$PATH"
    

    That probably only makes sense when you run Maven more than once in the script.

Related