Executing system commands on Linux

Hi,
I am trying to copy a file from Java code on Linux platform using the cp command.
Process p = Runtime.getRuntime.exec("bash -c \"cp file1 file2\"");
The process is exiting with exit code 2 and the file is not getting copied.
The same command when executed directly from the terminal window (command console of Linux) is working fine and the file is getting copied.
I am using RedHat Linux 7.1. Any ideas plz...
best wishes
Issac

try splitting up the args into an arary
import java.io.*;
public class CP {
  public static void main (String [] args) {
    try {
      String [] cmd = {"/bin/sh","-c","cp file1 file2"};
      Process p = Runtime.getRuntime().exec(cmd);
      p.waitFor();
      System.out.println("exit value " + p.exitValue());
    } catch (Exception e) {
      System.out.println("err : " + e);
}

Similar Messages

  • Executing system commands like cd on Linux from Java Code

    Hi,
    I need to execute a few system commands (like cd, ls, tar, etc.,) on RedHat Linux 7.1 from Java code. Any ideas plz.
    best wishes,
    Issac

    Since this thread mentioned using the DOS START command
    from an exec(), I was wondering whether anyone else is
    seeing the odd behavior I am.
    Most of the examples showing how to read stdout and stderr
    while the process is running show simple loops that use
    getInputStream and getErrorStream and do read's until they
    get back -1. Most of these examples are insensitive to the
    state of the Process.waitFor that happens elsewhere and sort
    of rely on the -1 and the waitFor happening roughly together.
    Whenever I use this technique to launch an arbitrary DOS
    command (e.g. Runtime.exec("dir")), it works fine, and
    everything seems to terminate as expected.
    However, when my command is something like:
    Runtime.exec("cmd /c start my.bat")
    where I deliberately use the START command to fork off
    a different process, something odd happens.
    Those simple read loops get an initial burst of stdout/stderr
    bytes from the "start" part of the command. But then eventually,
    these loops do a "read" which blocks on those InputStreams. Now,
    even if my Process.waitFor returns (because the start returned
    immediately), those read loops stay blocked **until that script
    started by 'start' runs to completion**. It is like the child
    of the child is holding those streams open somehow.
    I found that by doing something like an InputStream.available() or
    a BufferedReader.ready( ) check before dropping into the read,
    and allowing the Process.waitFor completion to exit those read loops,
    them I get what I expect -- namely immediate return from the START,
    but apparently complete copies of stdout and stderr.
    Curiously, in the case where the reads block until the child process
    started by START terminates, they still don't get the child's/child's
    stdout and stderr. It is just a long duration thread block that
    yields no data.
    Can anyone explain what is happening to a
    Process.getInputStream( ).read()
    when the process immediately does a START and returns? Why would
    the read( ) stay blocked when the START finished launching a new child
    process?
    ... ron cain

  • Execute system command line instructions

    Hi,
    suppose that my java program has to execute a system command line instrction(let's say dir/p for dos or ls * f or linux)
    how can we execute these system command line instructions programmatically from within a java program?
    thanks indeed for helping...

    i want to thank jfbriere for the usefull link he/she provides me with. 1- He
    2- You're welcome :-)

  • Operating System commands for LINUX OS

    Hi,
    I am working on PI7.1 OS LINUX,i am clear about WINDOWS OS how to call and execute but not clear with Linux OS
    Just trying one POC kind of requirement with Operating System Commands
    first i started with simple requirement moving one file from one directiry to other directiory,but unfortunaltly i was not sucesfull.
    the help documentation also not clear ,could you please any one give some clear clue to hoW  to call shell script.
    i have created below script.
    #!/bin/sh                                                                                cd /Interface                                                                               
    cat BIA1.xml >> /interfaces/BIA2.xml  
    http://wiki.sdn.sap.com/wiki/display/XI/SAPXIFileAdapterOSCommandLine+Feature
    thanks,
    Raj

    hi its very simple,just copy .sh file in PI server and call just sh path.it will work

  • Executing System Commands In Java

    Hi,
         I am not sure if this is a bug � or I am just doing this wrong. I have
    written a program to move files into ~/.trash/ . My problem is that this
    works only for files without spaces � but for files with spaces it will
    not work. Some of my code is below.
    I have temporarily uploaded the complete file at
    http://www.geocities.com/carmaski/Remove.java
    public static void main(String args[]) {
    String currDir = System.getProperty("user.dir") + "/";
    String trashDir = "\" \"/home/masca/.trash/";
    String commandString = "";
    for (int i = 0; i < args.length; i++ ) {
    File tmpFile = new File(currDir + args);
    if(tmpFile.exists()) {
    commandString = "mv \"" + currDir + args[i] + trashDir
    + args[i] + getTimeTag() + "\"";
    System.out.println("The command would be -- " +
    commandString);
    try {
    Process p = Runtime.getRuntime().exec(commandString);
    catch (IOException e) {
    e.printStackTrace();
    System.exit(-1);
    As an example I tried � this with a file that has a space � and I get
    the following output.
    The command would be -- mv "/home/masca/WORK/Text File"
    "/home/masca/.trash/Text File_2005.04.17_04hrs:25mins:36secs"
    However the file remains without being moved.
    I cannot understand why the mv command does not work in java. If I
    manually copy this to the command line I can get the file to work. It
    should be noted that this program works perfectly if the file does not
    have a space.
    Regards,
    Rio

    Use File.separator or simply / instead of Windows
    backslashes.
    - SaishI think OP is on a unix machine, and he still needs to escape the spaces. The escape character is, of course, a back-slash.
    Depending on the shell (my experience is with bash), to execute the command mv Test File.txt newTest File.txt, the file names either need to be double-quoted so that the command shell will treat them as a single token (I think that will work), or the spaces need to be escaped (I know that will work). In java, to include a single \ in a literal String, you need to escape the escape character, which is why I think two \\ are needed in the String, so that one will survive to be passed on to the exec command.
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Executing system commands query

    I'm only just starting to program Java although I do have a good grounding in programming other languages so it is probably more a question of familarity, but hopefully someone can answer this problem I am having.
    What I am trying to do is to execute TFTP on a Windows NT machine roughly every 5 seconds to get a file. To do this I have created a thread and within "public void run" I have a loop which contains something along the lines of:
    Runtime.getRuntime().exec( "C:\\WINNT\\system32\\tftp.exe <ipaddress> get <filename>" );
    Where I would specifiy a real IP address and filename.
    I then do a sleep on the current thread to make it pause for a while.
    The good news is it fetches the file every few seconds as I wanted. The bad news is it creates a new TFTP process each time and so it keeps using more and more memory.
    Now I'm sure there are better ways to do this but I am working things out as I go along. The finished program will use an infinite loop which will run out of memory.
    Can anyone recommend a solution or method to do this? Should I not bother with the thread, and what would be the best method to make it pause without killing processor time?
    If possible can anyone mail me directly. Thanks in advance.
    Mark.

    No I must quite specifically use TFTP. The scenario is information is entered via a FORM on a web page. The data is passed from the client to a server where I parse it using perl and write out the data in the necessary form to a file.
    The java file I am writing then runs continually fetching this file every few seconds for another program to read. The other program reads the data every few seconds and uses one of the fields in the file to identify if it has changed since the last time it was fetched, if so it can act on the new data.
    Using TFTP I can call it with a command line function to invoke TFTP to connect and fetch a file in one line. This seems much simpler using an existing executable than hand crafting code to do the same job.
    I've managed to write something in C++ which performs the task. Java seems a bit more ackwared as it discourages you using system commands as it means the code is not portable.
    However I originally wrote this as a Java file to expand my knowledge and as such I would like a proper solution.
    Thanks for the suggestion though. I will have a look just out of curiosity now.
    Mark.

  • How to execute system command from java program

    Hi all,
    I want to change directory path and then execute bash and other unix commands from a java program. When I execute them separately, it's working. Even in different try-catch block it's working but when I try to incorporate both of them in same try-catch block, I am not able to execute the commands. The change directory command works but it won't show me the effects of the bash and other commands.
    Suggestions??

    The code I am using is....
    try
    String str="cd D:\\Test";
    Process p=Runtime.getRuntime().exec("cmd /c cd
    "+str);your str string is already having cd in it but again you ar giving cd as part of this command also please check this,i will suggest you to remove cd from str
    Process p1=Runtime.getRuntime().exec("cmd /c mkdir
    "+str+"\\test_folder");you should say mkdir once you change your path,but here you are saying mkdir first and then cd D:\Test(this is because of str)..please check this
    Process p2=Runtime.getRuntime().exec("cmd /c bash");
    Process p3=Runtime.getRuntime().exec("cmd /c echo
    himanshu>name.txt");
    catch(IOException e)
    System.err.println("Error on exec() method");
    e.printStackTrace();
    Message was edited by:
    ragas

  • How to execute System command through Applet

    Hi all,
    How can I execute a System command through Applet.
    I have written a code Runtime.exec("ls") in my applet but it gives me
    this execption even if I certify the applet ->
    java.security.AccessControlException: access denied (java.io.FilePermission <<ALL FILES>> execute)
         at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
         at java.security.AccessController.checkPermission(AccessController.java:399)
         at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
         at java.lang.SecurityManager.checkExec(SecurityManager.java:802)
         at java.lang.Runtime.exec(Runtime.java:548)
         at java.lang.Runtime.exec(Runtime.java:418)
         at java.lang.Runtime.exec(Runtime.java:361)
         at java.lang.Runtime.exec(Runtime.java:325)
         at Test.init(Test.java:24)
         at sun.applet.AppletPanel.run(AppletPanel.java:344)
         at sun.plugin.navig.motif.MotifAppletViewer.maf_run(MotifAppletViewer.java:123)
         at sun.plugin.navig.motif.MotifAppletViewer.run(MotifAppletViewer.java:119)
         at java.lang.Thread.run(Thread.java:484)
    Thanks,
    Manoj.

    There should be a lesson about this somewhere.
    When you visit a web page, does it ask you if you want to have an applet loaded?
    Answer: No
    So, if you visit a page, and an applet is silently loaded which can then execute commands on your computer, is this good?
    Answer: No
    So why do you want to do this?
    Is it good for anyone?
    I mean, if I want to do "ls", can't I just open a command line? Do I need an applet to do it for me?
    Either you have devious desires or your hacking together something that probably shouldn't be.
    If you want to learn start here:
    http://java.sun.com/docs/books/tutorial/security1.2/index.html
    With the article entitled:
    Quick Tour of Controlling Applets
    Ian

  • Show progress bar while executing scp command in linux

    I am being trying to execute scp command throug java frames, I want to know is there any way to show progress when i am copying a file to another system.
    The scp command shows the progress in command prompt can i implement that on the jprogressbar.
    thanx in advance.

    I am being trying to execute scp command throug java frames, I want to know is there any way to show progress when i am copying a file to another system.
    The scp command shows the progress in command prompt can i implement that on the jprogressbar.
    thanx in advance.

  • Executing system commands and capturing results

    How do I get the result of executing a system command using Runtime? For example, if I execute "cmd /c dir", how do I get to the result of the dir command from the Process that is returned?

    Process p = Runtime.getRuntime.exec("...");
    InputStream in = p.getOutputStream();
    // now read the "in" stream just as you would any
    other stream.Slight typo getRuntime(), but it's close...

  • Supressing Dos window on executing system command

    Hey,
    is there any way to supress the dos window when I call a system dependent .exe or bat file?
    AND
    is there any way to run a .exe file as a background process so that no window of it pops up?
    I use the Runtime.exe() to execute the system command but I'm annoyed by the dos windows it opens up.
    Any help highly appreciated.

    This is an AGE OLD Issue which Sun keep burying. By burying I mean it has been the top of their bugs/requests list many times. They just decide its closed without making any such fixes. The community is not pleased with Suns actions in this respect, blowing off their highest rated request.
    Answer:
    If you start your program with java.exe, then you wont get that window when you do runtime commands. If you start with javaw.exe, you will. They are blaiming it on M$ but most feel its just a silly Sun position and lame attempt to put somethign on M$ that is not really on M$. Sun can do it but they feel their solution is unstable. Most people have ended up making .exes to replace java.exe to get rid of that hideous console window. JBuilder has an interesting (but not my type) solution.
    If you search the top 10 bugs/ requests this one has likely resurfaced as Sun keeps erasing it, but the people keep voting it back to the top...

  • Execute System Commands

    Hey all
    I need to write Java application that executes windows system commands. In the following example I tried to execute the command DATE /T but i got an exception. Could any one help ?
    import java.io.*;
    public class Shell {
        public static void main(String[] args) {
            String s = null;
            try {
                Process p = Runtime.getRuntime().exec("date /t");
                BufferedReader input = new BufferedReader(
                        new InputStreamReader(p.getInputStream()));
                System.out.println("Here's the standard output of the command: ");
                while ((s = input.readLine()) != null) {
                    System.out.println(s);
            } catch (IOException e) {
                e.printStackTrace();
    }

    hi,
    give command as "cmd /c date /t"
    to execute any dos commands using exec() method, you have to send those commands as parameters to the cmd.exe .
    regards,
    Mahender

  • Executing system command thru command line by passing it to a server

    Hello,
    I would like to know if there is any way by which I can call a system command through a java program . This system command takes parameters. If yes then how do i pass these paramaeters. This program will be called thru a sheel scripts and the parameters may vary...

    If I just look at the question in your post, I would say the answer is to call Runtime.getRuntime().exec("the system command"). But the title of the post mentioned passing it to a server; I won't attempt to answer that without knowing what it's all about.

  • Execute system commands from LabVIEW

    Hi,
    can anybody please help me with how to execute sytem commands from labview
    (WIn98 in particular).
    Basically I would like to execute the command "javac example.java"
    Looking forward to responses.
    Please be kind enough to send me a email also
    manjul [email protected]

    Oops. Looks like I lost the attachment on the way. Sorry... Here it comes
    Attachments:
    Command_Execution.vi ‏21 KB

  • Executing System commands

    Hello,
    I have a scnerio where I have to execute a Shell command like
    "ping 192.168.0.26" but I think in Java 1.4 the System.execute() method is
    deprecated. I used the Runtime command like this
    Process p;
    p = Runtime.getRuntime.exec("ping 192.168.0.26");but it shows me nothing on the console window. I want the output to be in the console window. How can I do that???

    Now I here is what I was trying before
    import java.io.*;
    public class test{
         public static void main(String[] args){
              Process p;
              String cmd = "ping 192.168.1.1";
              OutputStream out;
                           try{
                                 p = Runtime.getRuntime().exec(cmd);
                                   catch(IOException e){
         e.printStackTrace();
    }What else should be added to it

Maybe you are looking for

  • IMac and internet sharing issue

    Under System Preferences_Internet & Sharing_Sharing, I have the internet sharing box checked, along with screen sharing. Whenever I turn on my computer, the internet sharing is disabled, although the box is still checked. Once I re-check the box, it

  • Ipod Classic 120gb inbuilt recording capabilities

    I have had my Ipod classic 120gb for about 4 years. Although I am aware that it had the capcaity to record when used with an external mic, I found that I was actually able to use it to record without such equipment before. About a year ago, there was

  • HELP with BlackBerry Curve 8520, White screen after update to App World 2.0

    Hi, need an answer as soon as possible please. i downloaded the app world 2.0, after that i was told to restart. I didt, but, now i just have a White screen with the little clock on it... please... need an answer now, because my BB ys my world... Bus

  • Charging iPod with lid closed

    I was previously able to charge my ipod while the lid was closed on my laptop. Now, however, I am unable to do this. I am now required to leave my laptop open overnight just to charge the ipod. Can't remember when this started happening. I know i was

  • Embedded CRXI in Websphere running on iSeries - Error

    Hi, I have been using the new CR4E that I downloaded and installed on Websphere toolkit in windows. My reports have been working in my developement WAS server 6.1 & can export to PDF. But after deploying to my production WAS 6.1 server, I could not a