Search code examples
mavenbatch-filecmdexit-code

How to prevent Maven from exiting console in Windows?


env: Windows 10, Java 11.0.10, Maven 3.8.1

There is a simple batch file run.bat

mvn clean package
echo After build

When executing call run.bat from command line I get the full output of maven build, but the line After build is never printed to console. The last line of the output is Process finished with exit code N (where N=0 if build is successful and N=1 otherwise).

One of the possibilities is using start to run maven in a separate process, but the problem is the sequential execution is needed:

mvn clean package
command X            // depends on the previous command artifact

And I am not sure how to achieve that, assuming Maven calls exit internally.

Is there a way to execute mvn commands in sequence with other commands in the same script?


Solution

  • When you run mvn, what you are in fact doing is running a batch file named mvn.cmd. When you run a batch file from another, if you wish to return to it upon completion, you need to use the Call command.

    call mvn clean package
    echo After build
    

    The main issue is caused due to the default position of cli 'man' pages not telling their end users what they're running or how to properly do so. They determine that command line use, means typing directly into that interface, and therefore tries to help by minimizing the amount of typing you need to perform. In order to achieve that, they assume that you have not modified your %PATHEXT% variable, and often expect you to modify your %PATH% variables.

    However when you use a batch file, you only ever need to type your commands once, which means that the need to reduce that typing has much less importance. It is also quicker for a command to run using the extension and full path, than to allow for those things to be searched for at execution time. That said, this would be the recommended way to perform your task from a :

    Call "%ProgramFiles%\Maven\apache-maven-3.8.1\bin\mvn.cmd" clean package
    Echo After build
    

    To quickly explain what %PATHEXT% does; when you run mvn, the system will look for a file in the current directory named mvn, if that doesn't exist, it will read the %PATHEXT% variable, and append each extension listed in its value, in order, first to last, until it locates a file it can run with that extension. It will run only the first one it finds.

    If there isn't one found in the current working directory, it searches each of the locations listed in the values under %PATH%, also in order, first to last. It will run the first one it finds, appending the %PATHEXT% values as before.