How to run UNIX shell script in JAVA?


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 14 of 14

Thread: How to run UNIX shell script in JAVA?

  1. #1
    Join Date
    Oct 2005
    Posts
    4

    How to run UNIX shell script in JAVA?

    I need to run UNIX script using JAVA.
    Requirement is like that UNIX script will return an integer value and I have to read that integer value in java code and use that integer for further processing.
    I don't have any idea about this. Please help me out of this situation with code example.

    Thanks in advance.
    Ashish

  2. #2
    Join Date
    Oct 2005
    Posts
    22
    You can run it using exec method of Runtime Object. use this is in your code.

    Runtime r = Runtime.getSystemRuntime();
    r.exec("whatever you want to run");

    Thanks
    G.Rajasekhar

  3. #3
    Join Date
    Oct 2005
    Location
    New Jersey
    Posts
    255
    Here's a reference you should read as a precaution:
    http://www.javaworld.com/javaworld/j...229-traps.html
    Happiness is good health and a bad memory.

  4. #4
    Join Date
    Feb 2009
    Posts
    10

    Question Executing Linux Commands

    I cannot execute Internal Bash commands using runtime.exec()......
    eg. cd, etc....
    Please give me an alternative for this......

  5. #5
    Join Date
    Apr 2007
    Location
    Sterling Heights, Michigan
    Posts
    8,666
    Quote Originally Posted by mihir123 View Post
    I cannot execute Internal Bash commands using runtime.exec
    What errors are you getting when you try?
    I don't answer coding questions via PM or Email. Please post a thread in the appropriate forum section.
    Please use [Code]your code goes in here[/Code] tags when posting code.
    Before posting your question, did you look here?
    Got a question on Linux? Visit our Linux sister site.
    Modifications Required For VB6 Apps To Work On Vista

  6. #6
    Join Date
    Sep 2004
    Location
    Surrey, UK
    Posts
    21
    Ashish,

    I use the following code to execute commands in a Unix shell. It can deal with almost everything you can run at the shell prompt:

    Code:
    import java.io.InputStream;
    ...
    String cmd = "ls -l"; // this is the command to execute in the Unix shell
    // create a process for the shell
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true); // use this to capture messages sent to stderr
    Process shell = pb.start();
    InputStream shellIn = shell.getInputStream(); // this captures the output from the command
    int shellExitStatus = shell.waitFor(); // wait for the shell to finish and get the return code
    // at this point you can process the output issued by the command
    // for instance, this reads the output and writes it to System.out:
    int c;
    while ((c = shellIn.read()) != -1) {System.out.write(c);}
    // close the stream
    try {shellIn.close();} catch (IOException ignoreMe) {}
    Instead of "bash" you can use a program or script name (replacing "-c" and cmd with the appropriate arguments for the program or script), but then you won't be able to execute commands like ls.

    Mihir123, the code above could even execute a cd command, but on its own it has no effect.

    The command is executed in a new shell so it will affect only that shell instance; it will run without errors, effectively changing the directory, but once executed the shell closes and the directory change is forgotten.

    You should put the cd together with the other commands that need the directory change in a script and run that script instead.

    Alternatively you can redirect stdin of the shell process to an output stream and write commands to this stream. In this case do not use "-c" and cmd.

  7. #7
    Join Date
    Feb 2009
    Posts
    10

    Java in Linux

    Thanks very much for your code....it really helped me in a great way.

    As you said how can i change a directory using cd and simultaneously run another program or script like find, uname, ls, etc......

    Secondly do you know how can i replace special characters like (",\,',$) etc. in a String in java...........with a space or blank ...........

    Kindly reply as soon as possible plzzzzz.....

  8. #8
    Join Date
    Sep 2004
    Location
    Surrey, UK
    Posts
    21
    Mihir123,

    To change the directory (and keep this change effective while you execute other commands) put everything in a shell script and execute this script. For instance something like this:

    Write these lines in a file called test.bash (this file must have execution rights)
    Code:
    cd /home/mydir
    ls -l
    Then execute the code above using:
    Code:
    String cmd = "test.bash";
    To replace characters in a String in Java use string.replaceAll(regex, replacement), where regex is a regular expression representing the characters you want to replace and replacement is the String that will be put in place of all the instances of regex found in string. For instance:
    Code:
    string.replaceAll("[\"\\'\\$]", " ");
    You could also use a series of string.replace(oldChar, newChar):
    Code:
    string.replace('"', ' ').replace('\\', ' ').replace('''', ' ').replace('$', ' ')
    (but this creates several unnecessary Strings)
    Last edited by jcaccia; 03-05-2009 at 09:18 AM.

  9. #9
    Join Date
    Feb 2009
    Posts
    10

    Java in Linux

    Thanks for your above code...........


    It means that if i write several commands of linux one after another in test.bash it can execute all the commands at one time and give their outputs.......am I right??

    Secondly can the above statement replace double codes or single codes??
    Since java does not understand double codes inside a string

    (for eg. find / -type d -name "mail") ..........this String cannot be passed inside java since it contains double codes inside the string itself........
    so i need to replace it with blank.........to run it through java.....

  10. #10
    Join Date
    Sep 2004
    Location
    Surrey, UK
    Posts
    21
    Mihir123,

    Quote Originally Posted by mihir123 View Post
    It means that if i write several commands of linux one after another in test.bash it can execute all the commands at one time and give their outputs.......am I right??
    Yep, just like the old DOS batch files.

    Quote Originally Posted by mihir123 View Post
    Secondly can the above statement replace double codes or single codes??
    Since java does not understand double codes inside a string
    Do you mean double quotes (")? You can put double quotes in a Java String llike this:
    Code:
    String cmd = "find / -type d -name \"mail\"";
    Replacing them with spaces will probably not work if they are required and is not needed if you read the string (from a file, user input, &c.).

  11. #11
    Join Date
    Aug 2012
    Posts
    2

    Exclamation

    i know this is old thread, but really need help, i googled all day long for a solution and i tried 100 different combinations but non seems to work.

    what is wrong with this code:
    Code:
    ProcessBuilder pb = new ProcessBuilder("dpkg","-l > lista.txt");
           try {
                pb.start();
            } catch (IOException ex) {
                System.out.println("greska: "+ex.getMessage());
            }
    }
    i want to execute only one bash script command and not entire shell script file. If someone could help me, i would be very grateful, i even registered my account on this forum because of this problem

  12. #12
    Join Date
    Feb 2011
    Posts
    1
    Well its easy man,

    You should be on a linux box for doing this.

    Java has a Runtime class using which you can execute commands.

    But in your case, what can be done is:

    Process processObj = Runtime.getRuntime().exec("sh yourScriptName.sh");

  13. #13
    Join Date
    Aug 2012
    Posts
    2
    i solved it one week ago, but thanks for reply anyway
    p.s i am on linux

  14. #14
    Join Date
    Apr 2007
    Location
    Sterling Heights, Michigan
    Posts
    8,666
    What did you do? Please post your resolution as it could help others with the same or similiar problem.

    Thanks.
    I don't answer coding questions via PM or Email. Please post a thread in the appropriate forum section.
    Please use [Code]your code goes in here[/Code] tags when posting code.
    Before posting your question, did you look here?
    Got a question on Linux? Visit our Linux sister site.
    Modifications Required For VB6 Apps To Work On Vista

Similar Threads

  1. Java vs. .Net. A questionnaire
    By Basil in forum .NET
    Replies: 1
    Last Post: 05-13-2005, 07:46 AM
  2. DevX does seem one sideded
    By Rob Abbe in forum Talk to the Editors
    Replies: 44
    Last Post: 01-13-2003, 03:57 PM
  3. Has Sun Given Up on the Desktop?
    By Lori Piquet in forum Talk to the Editors
    Replies: 114
    Last Post: 10-10-2002, 07:01 AM
  4. run java app on Linux at boot up
    By Alan Shiers in forum Java
    Replies: 3
    Last Post: 07-17-2002, 12:29 AM
  5. Replies: 1
    Last Post: 09-13-2001, 08:08 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center