How to run linux script from windows using Java program

Well I had an requirement where I wanted to run shell scripts from my windows server, that too trigerred by a java program. To run a linux script from windows, we do have tool known as cygwin.

Cygwin is a large collection of GNU and Open Source tools which provide functionality similar to a Linux distribution on Windows. You can download it here : Cygwin download

Now to run any shell script file we need to to run this command :

C:/cygwin64/bin/bash.exe c:/Downloads/SCRIPT_FILE

So we nee to pass the script file path to the bash.exe of Cygwin.

Now lets write a java code to trigger all this. We need to set environment variables pointing to the bin folder of Cygwin. In this example I am using ImageMigick’s shell scrip to convert an image into a cartoon.

 try {
			 String[] env = new String[] { "path=%PATH%;C:/Downloads/ImageMagick-7.0.2-Q16;c:/cygwin64/bin/" };
 
			Process p = Runtime.getRuntime().exec(
				      "C:/cygwin64/bin/bash.exe c:/Downloads/bash/cartoon" Input_File Output_File,env );
			try {
				p.waitFor();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try (InputStream is = p.getErrorStream()) {
				int in = -1;
				while ((in = is.read()) != -1) {
					System.out.print((char) in);
				}
			}
			try (InputStream is = p.getInputStream()) {
				int in = -1;
				while ((in = is.read()) != -1) {
					System.out.print((char) in);
				}
			}
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

So using process api of java we invoked Cygwin’s bash process which internally invoked the shell script

Mar Java Mit Java 🙂

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *