0

I have a .sh file stored in some Linux system. The full path of the file is:

/comviva/CPP/Kokila/TransactionHandler/scripts/stopTH.sh

I am tring to execute it by

Runtime.getRuntime().exec(`/comviva/CPP/Kokila/TransactionHandler/scripts/stopTH.sh`)

but it is throwing some exception.

I want to execute that file from my java program in an MS-Windows environment; is it possible?

5
  • 6
    It's not possible to run a Unix shell script natively in Windows, which is what you're trying to do -- you'll need to convert (not just rename) that Unix shell script to a Windows batch file (with a .bat or .cmd filename extension/suffix). Which exception is being thrown? Which version of Java are you using? Commented Jun 24, 2011 at 6:04
  • 3
    Always list exceptions when asking questions. Commented Jun 24, 2011 at 7:30
  • 2
    You mention both a Linux system and a Windows system. The shell script is located on your Linux system, right? And your Java application (which should launch the shell script) is located on the Windows system. Is that correct? Commented Jun 24, 2011 at 7:42
  • 4
    What is the "some exception". This is an important information! Commented Jun 24, 2011 at 7:44
  • offtopic, belongs on stackoverflow; btw, you cannot directly execute a shell script, you have to execute bash. Commented Jun 24, 2011 at 7:45

5 Answers 5

3

To execute a .sh script on Windows, you would have to have a suitable command interpreter installed. For example, you could install the Cygwin environment on your Windows box and use it's bash interpreter.

However, Windows is not Linux even with Cygwin. Some scripts will not port from one environment to the other without alterations. If I had a problem executing a script via Java in Linux environment, I would prefer to debug the issue in that environment.

Remember, you could start your Java process on Linux in debug mode and attach your IDE debugger in Windows to that remote process.

Sign up to request clarification or add additional context in comments.

Comments

3

Thanks everybody for your responses. I found a solution to the problem. For this kind of situation we need to bind my Windows machine to Linux system. Here is the code that worked:

public String executeSHFile(String Username, String Password,String  Hostname)
    {
        String hostname = Hostname;
        String username = Username;
        String password = Password;
        try{
            Connection conn = new Connection(hostname);
               conn.connect();
               boolean isAuthenticated = conn.authenticateWithPassword(username, password);
               if (isAuthenticated == false)
                throw new IOException("Authentication failed.");
               Session sess = conn.openSession();
              sess.execCommand("sh //full path/file name.sh");

               System.out.println("Here is some information about the remote host:");
               InputStream stdout = new StreamGobbler(sess.getStdout());
               BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
               while (true)
                {
                    String line = br.readLine();
                    if (line == null)
                        break;
                    current_time=line;
                    System.out.println(line);
                }

               System.out.println("ExitCode: " + sess.getExitStatus());
               /* Close this session */

                sess.close();

                /* Close the connection */

                conn.close();
        }catch(IOException e)
        {
            e.printStackTrace(System.err);
            System.exit(2);
        }finally{

        }
}

Thank you.

1 Comment

You use Connection/Session classes: which library are they from?
2

Here is my code. As the comment says, works on Linux, fails on Windows (XP). AFAIK the problem with Windows is that cmd.exe is weird regarding it's parameters. For your specific sub-task you probably can get it to work by playing with quotes and maybe embedding the sub-task parameters in the subtask itself.

/** Execute an abritrary shell command.
  * returns the output as a String.
  * Works on Linux, fails on Windows,
  * not yet sure about OS X.
  */
public static String ExecuteCommand( final String Cmd ) {
    boolean DB = false ;
    if ( DB ) {
        Debug.Log( "*** Misc.ExecuteCommand() ***" );
        Debug.Log( "--- Cmd", Cmd );
    }
String Output = "";
String ELabel = "";
    String[] Command = new String[3];
    if ( Misc.OSName().equals( "WINDOWS" ) ) {
        Command[0] = System.getenv( "ComSPec" );
        Command[1] = "/C";
    } else {
        Command[0] = "/bin/bash";
        Command[1] = "-c";
    }
Command[2] = Cmd;
    if (DB ) {
        Debug.Log( "--- Command", Command );
    }
    if ( Misc.OSName().equals( "WINDOWS" ) ) {
        Debug.Log( "This is WINDOWS; I give up" );
        return "";
    }
try {
        ELabel = "new ProcessBuilder()";
        ProcessBuilder pb = new ProcessBuilder( Command );
        ELabel = "redirectErrorStream()";
        pb.redirectErrorStream( true );
        ELabel = "pb.start()";
        Process p = pb.start();
        ELabel = "p.getInputStream()";
        InputStream pout = p.getInputStream();
        ELabel = "p.waitFor()";
        int ExitCode = p.waitFor();
        int Avail;
        while ( true ) {
            ELabel = "pout.available()";
            if ( pout.available() <= 0 ) {
                break;
            }
            ELabel = "pout.read()";
            char inch = (char) pout.read();
            Output = Output + inch;
        }
        ELabel = "pout.close()";
        pout.close();
    } catch ( Exception e ) {
        Debug.Log( ELabel, e );
    }

    if ( DB ) {
        Debug.Log( "--- Misc.ExecuteCommand() finished" );
    }
    return Output;
}

}

1 Comment

You should not have first character uppercased for methods and variables in Java.
1

I did a quick test here, the following works assuming you have /bin/bash on your machine:

my /tmp/test.sh:

#!/bin/bash
echo `ls`

my java code:

try {
    InputStream is = Runtime.getRuntime().exec("/bin/bash /tmp/test.sh").getInputStream();
    int i = is.read();
    while(i > 0) {
        System.out.print((char)i);
        i = is.read();
    }
} catch (IOException e) {
    e.printStackTrace();
}

output: all files in current directory

edit: i kinda overlooked that "execute from windows" comment. I don't know what you mean with that.

Comments

0

you may make a .bat file(batch file), that can run on windows. put the content of the .sh file in the .bat file start a process from your application like :

Process.Start("myFile.bat");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.