Runtime.exec() on shell script - unix

Hello all.
I'm gonna run a shell script and its parameter on unix solaris.
This is the whole command:
-> ex.sh "03/02/03 11:22:00"
'ex.sh' consists of the line like this.
-> ex date="$SSCREATE"
So, I expect "03/02/03 11:22:00" would be replaced with '$SSCREATE'
BTW, in Java class I invoke the shell in this way.
Process p = Runtime.getRuntime().exec("./ex.sh \"03/02/03 11:22:00\"");
InputStreamReader in = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(in);
But I can't get any output from this, I mean, when I use
'br.readLine()'
Why is that? Do I miss something?
Thanks in advance.

Thanks Jason.
Actually, I succeeded to run only 'whatever.sh'.(without any parameters) - No problems using Runtime.exec().
But, according what you wrote, is '/usr/bin/sh' a must as a prefix before real commnad line?
And what if the argumet has "(double quote) at the both ends?
I'd be glad if you show me the example.
Thank you again.

Similar Messages

  • Runtime.exec() - Need to execute unix command through pipe

    I want to execute something like this from Runtime.exec() :
    tar -czp -C /tmp/ myfile | ssh -qx -c blowfish remoteHost tar -xz -C /tmp/
    If I give the complete string as it is, then the system takes ssh command and the arguments to ssh (-qx) as arguments for tar and, thus, fails. I guess the reason is that the Runtime just takes the first string as the command and passes everything else as arguments to the command.
    How can I achieve this?

    The pipe symbol is interpreted by the shell, so you'd need the command you execute to be a shell (/bin/sh, /bin/csh /bin/bash, etc.) and the rest of it to be the args to that shell.
    Look at the man page for your shell. There should be a -c or somesuch argument that means "take the rest of this line as a command to execute in the shell I'm creating, which will then execute."
    Something like /bin/bash -c foo \| bar Not sure if you have to escape the pipe or not. Futz around with it and see.

  • How to invoke a shell script using java

    Hi
    I am trying to invoke a shell script(unix) using java and I have tryied to load the shell using exec(cmd) and then trying to execute the shell.
    But it is not working.
    Can you please guide me on this matter.

    Hi I am facing the same problem
    I want to call a shell script through java in linux system of course.
    I am using the following section of code .
    public class LinuxServer {
         public static void main(String args[]){
              Runtime r = Runtime.getRuntime(); //get runtime information
              try
              Process Child = r.exec("/usr/bin/ksh") ; //execute command
              BufferedWriter outCommand = new BufferedWriter(new OutputStreamWriter(Child.getOutputStream()));
              outCommand.write("/opt/jboss-4.0.0/test1.sh");
              outCommand.flush();
              try
              Child.waitFor(); //wait for command to complete
              catch(InterruptedException e)
              { //handle waitFor failure
              System.out.println("ERROR: waitFor failure");
              System.exit(10); //exit application with exit code 10
              catch(IOException e)
              { //handle exec failure
              System.out.println("ERROR: exec failure"+e);
              System.exit(11); //exit application with exit code 11
    But when I am compiling and running this script in the linux system,
    Its giving the following error.
    Exception in thread "main" java.lang.NoClassDefFoundError: while resolving class: LinuxServer
    at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.initializeClass() (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.forName(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at gnu.gcj.runtime.FirstThread.run() (/usr/lib/libgcj.so.5.0.0)
    at JvThreadRun(java.lang.Thread) (/usr/lib/libgcj.so.5.0.0)
    at JvRunMain(java.lang.Class, byte const, int, byte const, boolean) (/usr/lib/libgcj.so.5.0.0)
    at __gcj_personality_v0 (/opt/jboss-4.0.0/java.version=1.4.2)
    at __libc_start_main (/lib/tls/libc-2.3.4.so)
    at JvRegisterClasses (/opt/jboss-4.0.0/java.version=1.4.2)
    Caused by: java.lang.ClassNotFoundException: java.lang.StringBuilder not found in [file:/usr/local/staf/lib/JSTAF.jar, file:/usr/local/staf/samples/demo/STAFDemo.jar, file:/home/db2inst4/sandip/staf/lib/JSTAF.jar, file:/home/db2inst4/sandip/staf/samples/demo/STAFDemo.jar, file:/usr/share/java/libgcj-3.4.3.jar, file:./, core:/]
    at java.net.URLClassLoader.findClass(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at gnu.gcj.runtime.VMClassLoader.findClass(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.ClassLoader.loadClass(java.lang.String, boolean) (/usr/lib/libgcj.so.5.0.0)
    at JvFindClass(_Jv_Utf8Const, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
    at JvBytecodeVerifier.verify_instructions_0() (/usr/lib/libgcj.so.5.0.0)
    at JvVerifyMethod(_Jv_InterpMethod) (/usr/lib/libgcj.so.5.0.0)
    at JvPrepareClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at JvWaitForState(java.lang.Class, int) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.VMClassLoader.linkClass0(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    ...9 more
    Pls help

  • Runtime exec fail()

    I exec() an shell script, which is not executable. I would like to know how can I handle the exception. I would like to use the getErrorStream() when there is an error. I do not know how do I set it up?
    Thanks

    From the Runtime.exec documentation:
    Starting an operating system process is highly system-dependent. Among the many things that can go wrong are:
    The operating system program file was not found.
    Access to the program file was denied.
    The working directory does not exist.
    In such cases an exception will be thrown. The exact nature of the exception is system-dependent, but it will always be a subclass of IOException.
    Catch and handle the exception. Follow the methods in this tutorial:
    http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

  • Execute txkWfClone.sh in a shell script

    We have a requirement that needs txkWfClone.sh to run inside a shell script (unix). We need to pass the username/password in the shell script. Basically we need to run this as a silent process.
    Any suggestions on how to accomplish that?

    900441 wrote:
    We have a requirement that needs txkWfClone.sh to run inside a shell script (unix). We need to pass the username/password in the shell script. Basically we need to run this as a silent process.
    Any suggestions on how to accomplish that?Yes.
    How to Change the System Name in Workflow? [ID 387337.1]
    Txkwfclone.Sql Script Is Receiving The Parameters In Incorrect Order [ID 880264.1]
    You may also view the script and you will find if any parameters need to be passed.
    Thanks,
    Hussein

  • Statspack report generation shell script?

    Does anyone have a shell script (unix/solaris) which does the following:
    Gets the snap_ids from the 09:00 and 17:00 statspack snapshots (from today or yesterday), and runs spreport.sql, using these snapshot ids as begin_snap and end_snap.
    I do not want to purge any snapshots from the database. I simply want to generate a daily "9 to 5" statspack report every day.
    TIA,
    Dave

    Hi,
    You can do the following way:
    1. Write script to get the begin snap_id as:
    $cat > begin_snap.sql
    set head off
    set echo off
    set verify off
    set termout off
    spool begin_snap_id.log
    SELECT snap_id
    FROM stats$snapshot
    WHERE TRUNC(snap_time) = TRUNC(SYSDATE-1)
    AND TO_NUMBER(TO_CHAR(snap_time,'HH24')) =9;
    spool off
    2. write a script to get end snap id as same as above substituting 9 with 17 with script name as end_snap.sql and spool file name as end_snap_id.log.
    3. write a script to pass arguments for spreport.sql as:
    cat > statspack_report
    #!/bin/ksh
    ORACLE_HOME=/home/oratest
    TODAY=`date '+%Y%m%d' `
    REPORT=report_${TODAY}.txt
    sqlplus -s perfstat/perfstat@database_name @$ORACLE_HOME/begin_snap.sql <<EOF
    EOF
    BEGIN_ID=`cat /home/oratest/begin_snap_id.log | sed '/^$/d' `
    sqlplus -s perfstat/perfstat@database_name @$ORACLE_HOME/end_snap.sql <<EOF
    EOF
    END_ID=`cat /home/oratest/end_snap_id.log | sed '/^$/d' `
    sqlplus -s perfstat/perfstat@database_name @$ORACLE_HOME/rdbms/admin/spreport.sql <<EOF
    ${BEGIN_ID}
    ${END_ID}
    ${REPORT}
    EOF
    you can schedule this statspack_report in a crontab.
    thanks
    srinivas.

  • HELP with Shell scripting!!!

    Hello all,
    I'm very new to shell scripting and I'm trying to learn a little more as I go on. I'm trying to write a shell script to create a symbolic link to an application and have it moved to the current user's desktop. I've been doing some testing with the default applications installed on Leopard here is what I have so far...
    ls -s /Applications/Chess.app
    I've trying using cp commands, but I continue to get error messages. The above script does create a symbolic link to my home directory, but I want to then move it from the home directory to the current user's desktop. Can anyone lead me any further?
    Thanks in advance for any help!

    I'm also having a problem making my shell script unix executable. I have tried chmod +x path/to/script and then I killall Finder but nothing happens. Am I doing something wrong?
    Are you trying to make your script "Double-Clickable"?
    Then you still need to do the
    chmod +x /path/to/script
    But that will just make it something you can run from a shell.
    If you want double-clickable, you can create an Automator app
    Applications -> Automator -> Run Shell Script
    Or you can download the free Platypus utility that will make any script a double-clickable applications.
    Or you can name your script
    myscript.command
    where the .command is the important part, which the Finder will treat as something it should execute as a shell script when double-clicked.
    And no killing Finder. They will work without messing with the Finder.
    Personally, I prefer the Automator app or Platypus. Well I also work a lot in the shell, and I execute scripts as script in the shell all the time, so I only create a lot more scripts that get executed as commands than I do double-clickable scripts.

  • Runtime.exec using extended envp

    Hello,
    I would like to call Runtime.exec(String[], String[]), using the already existing environment variables with some modifications. Anyone have a tip how to accomplish this?

    ugly hack, yes but it should work:
    in pseudocode:
    Process p = Runtime.exec(my Shell's name);
    p.getOutputStream().write("setenv stuff"); // do this to modify your enviornment
    p.getOutputStream().write("my executable");
    That would allow you to modify the enviornment of your child process.

  • Runtime.exec with a unix shell script

    I've done a lot of google'ing and haven't found a definitive answer to my question, including the JavaWorld article that is pointed to quite often. Scenario1 - The program calling Runtime.exec is running in /dir1 and I have a script called test.sh in /dir2 (neither directory are in the path). If I call Runtime.exec("test.sh", null, "/dir2"), I get java.io.IOException: test.sh: not found. However, if I do "touch test.sh" AND "chmod +x test.sh" in /dir1 and call the same exec, it works AND runs the script in /dir2 not /dir1?!?! Also, if I copy /dir2/test.sh /dir1/test.sh and I call exec("test.sh"), it works fine. Scenario2 - If I get rid of /dir1/test.sh and call exec("/dir2/test.sh", null, "/dir2") OR exec("/bin/sh test.sh", null, "/dir2") - both of those work. I just don't get Scenario1. Why does having the dummy executable test.sh in /dir1 allow it to run in /dir2 OR if the script is in the local directory of the process calling exec, why does it work without adding the path? It doesn't seem consistent. Seems like the working directory I specify isn't set before trying to run it or something. On the flip side, if I have a java class in /dir2 called test.class, I can call exec("java test", null, "/dir2") and it just runs without jumping through any hoops - although I think the explanation for that is that "java" is in the path. Let me know what you think.
    Gary

    I think the problem is that the three argument version of exec specifies the command to run (should be full path to it if it is not in the current dir), the environment, then the working directory. The working directory will not help java to find the command to run in the first place. The following does work as you say:
    Runtime.exec("/bin/sh test.sh",null,"/dir2");This is because the full path to the command (/bin/sh) is specified, that runs in directory /dir2 then tries to find test.sh which it finds there.
    Basically to run anything, you should specify the full path in the command, the working directory will not help java find it.
    Dave

  • Java exec() of UNIX shell script

    I have a java application that uses:
    p = Runtime.getRuntime().exec( cmdLine);
    to execute a UNIX shell script, for example:
    #!/bin/ksh
    . /export/pc112477/freeware/work1/wsEnv
    export PATH=/opt/sfw/bin:/usr/ccs/bin:/usr/bin:/usr/ucb:$PATH
    cd /export/pc112477/freeware/work1/usr/src/pkgdefs/SFWnmap
    /usr/ccs/bin/make -e ROOT=$ROOT install
    RESULT=$?
    if [ $RESULT = 0 ]
    then
    echo "Package source"
    cd /export/pc112477/freeware/work1/usr/src/pkgdefs/SFWnmapS
    /usr/ccs/bin/make -e ROOT=$ROOT install
    RESULT=$?
    fi
    exit $RESULT
    Some times the running of the script locks up depending on how much work the script has to, eg. if the make calls pkgmk for a small package it runs okay but if its a large package it locks up in pkgmk.
    The script itself works okay if run directly
    Does anyone have any ideas on why this locks up and how I could stop it doing it.
    Thanks

    For anyone who stumbles across this and needs an answer:
    To empty the standard error and output, you need to use getErrorStream() and getInputStream() on the Process object created when you execed your command. Create new InputStreamReaders with the streams from the process, then wrap those with BufferedReaders and read each line with a while loop. This is the basic thing you need to do:
    try{
    Process proc = Runtime.getRuntime().exec(command);
    InputStreamReader isr = new InputStreamReader(proc.getErrorStream());
    BufferedReader errReader = new BufferedReader(isr);
    String line;
    while((line = errReader.readLine()) != null)
    <do something with each line of error>
    } //end try
    catch(<errors>) {
    <do something with errors>
    } //end catch
    What you really should do is put the stream handling in a separate class that extends Thread, create an instance for the error and output streams, and start each one. There is a class called StreamGobbler that does this sort of thing. Look at http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html to find out more about it and read a detailed explanation of different problems with exec().

  • Parameter  to shell script using Runtime.exec(string)

    Hi all, ( Speciall hi to dheeraj tak )
    Briefly : How do i pass an arguement to a non - java executible being called using Runtime.exec.
    In detail : i am using Runtime.exec to call a shell script : The code is as follows:
    String callAndArgs[] = {"/home/tom/jakarta-tomcat-4.1.24/webapps/dash/script.sh"};
    try {
    Runtime rt = Runtime.getRuntime();
    Process child = rt.exec(callAndArgs);
    This works properly & calls the shell script which in turn invokes some other executible (c file).
    $HOME/midi/test/build/bin/<C-EXECUTIBLE>
    Here i am specifying the name (say hello.exe ) . So far so good.
    I want to make this happen dynamiclaly. so i need to pass the name of the executible as a parameter to the script.
    To pass a parameter i hav to change the string to :-
    String callAndArgs[] = {"/home/tom/jakarta-tomcat-4.1.24/webapps/dash/script.sh <C-EXECUTIBLE HERE>"};
    and the script to
    $HOME/midi/test/build/bin/$1 --- where $1 refers to argument 1. (C-EXECUTIBLE AGAIN).
    This is giving an IO - Execption. Plz help
    Code will be very helpful.
    Thanx in advance

    some 1 plz tell me the difference :-
    This is the documentation of Runtime.exec that i found :-
    1> exec
    public Process exec(String command) throws IOException
    Executes the specified string command in a separate process.
    The command argument is parsed into tokens and then executed as a command in a separate process. This method has exactly the same effect as exec(command, null).
    Parameters:
    command - a specified system command
    Complete refernce says : Process (String progName) ----- Executes a program specified by programname as a seperate process.
    2> exec
    public Process exec(String cmdarray[]) throws IOException
    Executes the specified command and arguments in a separate process.
    The command specified by the tokens in cmdarray is executed as a command in a separate process. This has exactly the same effect as exec(cmdarray, null).
    Parameters:
    cmdarray - array containing the command to call and its arguments.
    Complete reference says : Process exec(String comLineArray[]) ---- Executes the command line specified bythe string in comLineArray as a seperate process.
    This means that there is provision 4 command line arguments...
    how do u use it then????????????????????????????

  • Runtime.exec with Unix script

    I want to execute unix script xxx.sh that I write it for running something and I will execute that script via java class I use
    Runtime runTime = Runtime.getRuntime();
    Process procRun = runTime.exec("/xxx/yyyy/testing.sh");
    xxx and yyyy is path in my unix server and testing.sh is unix script
    when I run this class it return true result but that unix script doesn't working or execute following my program in java class
    please help me to solve this problem
    Regards,
    sobig

    when I run this class it return true result but that unix script doesn't
    working or execute following my program in java classwhat do you mean it returns true....
    and how do you know that it does not execute your script.... its probably going to be started as a bg process.... try doing something like creating a directory or something in the script .sh to be sure that it ran.... (just for testing).... im quite sure that it will execute a .sh file like that....

  • Error while trying to execute a unix shell script from java program

    Hi
    I have written a program to execute a unix shell script in a remote machine. I am using J2ssh libraries to estabilish the session connection with the remote box.The program is successfully able to connect and authenticate with the box.
    The runtime .exec() is been implemented to execute the shell script.I have given below the code snippet.
    try {
         File file_location = new File("/usr/bin/");
         String file_location1 = "/opt/app/Hyperion/scripts/daily";
         String a_mib_name = "test.sh";
         String cmd[] = new String[] {"/usr/bin/bash", file_location1, a_mib_name};
         Runtime rtime = Runtime.getRuntime();
         Process p = rtime.exec(cmd, null, file_location);
    System.out.println( "Connected to the server1" );
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = br.readLine();
    while(line !=null)
    System.out.println(line);
    line = br.readLine();
    br.close();
    p.getErrorStream ().close ();
    p.getOutputStream().close();
    int retVal = p.waitFor();
    System.out.println("wait " + retVal);
    //session.executeCommand("ls");
    catch (IOException ex) {
    I get an error message
    Connected to the server
    java.io.IOException: Cannot run program "/usr/bin/bash" (in directory "\usr\bin"
    ): CreateProcess error=3, The system cannot find the path specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at SftpConnect.main(SftpConnect.java:143)
    Caused by: java.io.IOException: CreateProcess error=3, The system cannot find th
    e path specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    I am sure of the file path where the bash.sh and test.sh are located.
    Am i missing something? Any help would be greatly appreciated.
    Thanks
    Senthil

    Hi, I am using a simple program to connect to a RMI server and execute shell script. I use the Runtime.exec aommand to do the same.
    The script is sh /tmp/pub/alka/test.sh /tmp/pub/alka/abc/xyz/ul ul
    The script when run from the server, gives no errors. But when ran using rthe above method in java, gives errors as follows,
    Mycode:
    String command = "/bin/sh /tmp/pub/alka/test.sh /tmp/pub/alka/abc/xyz/ul ul";
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(command);
    int exitVal = proc.exitValue();
    System.out.println("Process exitValue: " + exitVal);
    java.io.IOException: CreateProcess: /bin/sh /tmp/pub/alka/test.sh /tmp/pub/alka/abc/xyz/ul ul error=3
         at java.lang.ProcessImpl.create(Native Method)
         at java.lang.ProcessImpl.<init>(Unknown Source)
         at java.lang.ProcessImpl.start(Unknown Source)
         at java.lang.ProcessBuilder.start(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at DecryptTest.main(DecryptTest.java:18)
    Can anyone please help

  • Error while executing unix shell script from java program

    Hi All,
    I am trying to execute unix shell script from a java program using Runtime.execute() method by passing script name and additional arguments.
    Code snippet :
    Java Class :
    try{
         String fileName ="test.ksh";
         String argValue ="satish"; // value passed to the script
         String exeParam = "/usr/bin/ksh "+fileName+" "+argValue;
         Process proc = Runtime.getRuntime().exec(exeParam);
         int exitValue = proc.waitFor();
         sop("Exit Value  is : "+exitValue);
    catch(Exception e)
    e.printStackTrace();
    }Test.ksh
      export -- application realated paths..
      nohup  abc.exe 1> test.log 2>&1;
      $1
      exit.By running the above java class , i am getting exit Value: 139 and log file test.log of 0 bytes.
    when i am running the same command (/usr/bin/ksh test.ksh satish) manually, it's calling abc.exe file successfully
    and able generate the logs properly.
    Pls let us know where exactly i am stuck..
    Thanks in advance,
    Regards,
    Satish

    Hi Sabre,
    As per the guidelines provided by the article, i had done below changes..
    InputStream is = null;
    InputStreamReader iStreamReader = null;
    BufferedReader bReader = null;
    String line = null;
    try{
    String fileName ="test.ksh";
    String argValue ="satish"; // value passed to the script
    String exeParam = "/usr/bin/ksh "+fileName+" "+argValue;
    Process proc = Runtime.getRuntime().exec(exeParam);
    is = proc.getErrorStream();
    iStreamReader = new InputStreamReader(is);
    bReader = new BufferedReader(iStreamReader);
    System.out.println("<ERROR>");
    while((line = bReader.readLine()) != null)
    System.out.println("Error is : "+line);
    System.out.println("</ERROR>");
    int exitValue = proc.waitFor();
    sop("Exit Value is : "+exitValue);
    catch(Exception e)
    e.printStackTrace();
    Now , it's showing something like..
    <ERROR>
    </ERROR>

  • How to execute unix shell script from Java ...

    Hi,
    Anyone know how to execute unix shell script from Java?
    Suppose I have several shell scripts written in perl or tcl or bash.
    I just want to catch the output of that script.
    Is there any ready to use module/object for this?
    Please let me know, this is quite urgent for my study assigment.
    Thanks in advance,
    Regards,
    me

    Look up Runtime.exec()

Maybe you are looking for

  • Error 500 and also getting an ISAPI error.

    Description of the Problem/Question: Here is the error message we are seeing in the extended logging on the webserver. We can replicate in our test environment and this log is from the test region. It throws an error 500, ISAPI error to the user. Her

  • XA8-50 (A5500-F) dims and turns off in sunlight.

    Anyone else experiencing this? I sit in the shade, reading, then the tablet screen turns dim and then the tablet dies. Hard reset worked one time. Now I cannot reset either. Help!

  • Digital Camera Not Recongized

    When I connect a camera to the MacBook Pro 15 Retina via the USB cable it is not being recognized. It does not show up in the bottom right under USB devices and it does not show up in Windows Explorer. When I go to Device Manager I see the camera und

  • Security patch MS11-049 needed for sql 2008 R2 SP2

    My Database engine version is: SQL Server 2008 R2(SP2) - 10.50.4260.0(X64)   Jul 11 2012 15:47:13   Copyright(c) Microsoft Corporation  Enterprise Edition(64-bit) on Windows NT 6.1 <X64>(Build 7601: Service Pack 1)(Hypervisor) According to KB2494086

  • Hide Tax Code in PO

    Dear All I want to hide tax code (for  example VL CST 1% ) from PO.Not  delete from FTXP.When I am creating PO Tax Code VL have been not visible in Tax menu help. Thanx & Regards, Dishant