How to automatically create batch / shell scripts

2019-01-23 17:16发布

问题:

I have a Java command-line application, and would like to create an Ant* build script that will create all the required batch/shell scripts to run the application successfully including all the classpath variables. I need it to do the following:

  1. Create a shell script file for Linux/Unix and a batch file for Windows/DOS
  2. Add all classpath dependencies (from Maven or simply use the build path in Eclipse)
  3. Add any necessary boilerplate sh/bat code to run (ENV variables, JAVA_HOME, etc.)

I found only a partial answer here.

But I haven't found anything that does this basic and trivial task that every build involves.

Disclaimer - the original question was Ant/Maven, but I would prefer to see if it can be done in Ant.

回答1:

In Maven the best solution for this is the maven-appassembler-plugin which handles the creation of a shell script / batch file. In combination with maven-assembly you can create a tar.gz or zip archive which contains everything which is needed.



回答2:

Maven knows the dependency:build-classpath goal, which does most of the dirty work:

mvn dependency:build-classpath -DoutputFile=cp.txt

You can use this generated file in a shell script to create the java classpath (I know, it ain't much, but it'll get you started).

Or you can use the exec-maven-plugin to launch a main class from the current maven context. Something like this will do:

mvn compile org.codehaus.mojo:exec-maven-plugin:1.2:java \
    -Dexec.mainClass=com.yourcompany.YourClass


回答3:

One approach is to use a binary executable builder for Java applications. Some of these can be launched from ant with provided ant tasks.

For example, exe4j can create executables for command-line applications, and supports Windows, Linux and Mac. The executable wraps the Java code, its classpath, and JVM search path. A custom ant task "com.exe4j.Exe4JTask" supports generation of the executable from an exe4J configuration -- which can be created with a friendly wizard.



回答4:

Apache commons Launcher creates startup scripts for you. Both Windows and Linux script will be generated. Also it can be integrated with Ant.

I hope it will help others.