Execute an Unix command with pipe

Hi,
How do I execute a unix command with pipe from JAVA runTime.exec(cmd)? for example: "ls -l |wc -l"
should return number of files. However, there is no output result. If I use "ls -l" as command argument, it gives file list.
Here is my program:
public static void main(String[] args) {
try {
Runtime runCmd = Runtime.getRuntime();
System.out.println("sys testing");
Process retProc = runCmd.exec(args[0]);
BufferedReader bread = new BufferedReader
(new InputStreamReader(retProc.getInputStream()) );
String out = bread.readLine();
while ( out != null ) {
System.out.println(out);
out = bread.readLine();
DataOutputStream outSt = new DataOutputStream(retProc.getOutputStream() );
outSt.writeChars(args[1]);
outSt.flush();
} catch (Exception ie) {
ie.printStackTrace();
Thanks in advance,
Jeff

I got my answer !
No need to reply

Similar Messages

  • How to run Unix command with Pipe ( | )?

    Dear Friends,
    I have to execute the below unix command through java program.
    *ps -ewwo pid,args | grep -E "abc.sh|xyz.jar" | gawk '{ print $1 }' | wc -l*
    My code to execute this command is,
    Runtime run = Runtime.getRuntime();
    File workDir = new File("/root/sat");
    String psCmd = "ps -ewwo pid,args | grep -E \"abc.sh|xyz.jar \" | gawk '{ print $1 }' | wc -l";
    Process process = run.exec(psCmd, null, workDir);
              String line;
              int i = process.waitFor() ;
              if(i == 0) {
              BufferedReader buf = new BufferedReader( new InputStreamReader( process.getInputStream() ) ) ;
              while ( ( line = buf.readLine() ) != null )
                   System.out.println("Line - ["+line+"]") ;
              } else {
                   BufferedReader stdErr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                   // read the output from the command
                   while ((line = stdErr.readLine()) != null) {
                   System.out.println(line);
                   }When i execute this command, i'm getting output as,
    ERROR: Garbage option.
    When i analyse the above error, i found that, the PIPE ( | ) command is not supported through java.
    Could anyone please help me how to execute the above unix command (with | ) in java?
    Thanks in advance,
    Sathish

    The pipe has to be interpreted by a shell so you need
    String[] psCmd =
        "sh",
        "-c"
        "ps -ewwo pid,args | grep -E \"abc.sh|xyz.jar \" | gawk '{ print $1 }' | wc -l"
    Process process = run.exec(psCmd, null, workDir);You should also read, re-read and then implement the recommendations in the 4 sections of http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html .

  • Executing multiple UNIX commands

    Hello
    I would like to execute from a Java application the UNIX command :
    ls -l | grep ob
    I first execute the command "ls -l" and write the output stream in the input stream of the command "grep ob"
    My problem is that the second command is waiting for the EOT character and i don't know how to send it. I tried to write the char 4 but it doesn't work
    Any idea to run commands with pipes ?
    Chris

    I reply to myself in case someone else wants to do that job :
        private static byte[] execUNIXcmd(String commande, byte[] outputData, boolean closeStream) {
         Runtime runtime = Runtime.getRuntime();
         Process process = null;
         InputStream inputStream = null;
         OutputStream outputStream = null;
         byte[] bBuf = null;
         try {
             process = runtime.exec(commande);
             outputStream = process.getOutputStream();
             inputStream = process.getInputStream();
             if (outputData != null) {
              outputStream.write(outputData);
             if (closeStream) {
              outputStream.close();
             inputStream = process.getInputStream();
             process.waitFor();
             bBuf = new byte[inputStream.available()];
             inputStream.read(bBuf, 0, inputStream.available());
             return bBuf;
         } catch (InterruptedException e) {
             System.err.println("ERROR : Enable to wait the process");
             return null;
         } catch (IOException e) {
             System.err.println("ERROR : Enable to read input lines");
             return null;
        // Fonction principale
        public static void main(String s[]) {
         byte[] result = null;
         result = execUNIXcmd("ls -l", null, false);
         result = execUNIXcmd("grep java", result,true);
         result = execUNIXcmd("grep ~", result,true);
         System.out.println(new String(result));
        }I missed to close the outputStream of the command waiting for it.
    Chris

  • At CRS-1,how can i use show command with pipe | ?

    HI,ALL
    when I use show command with pipe on the CRS-1,the command invalid
    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#show interfaces | include line |errors 
                                                                       ^
    % Invalid input detected at '^' marker.
    ========================================================
    But Previously on the cisco 7609,I can use the show command
    GZ-DM-SR-1.MAN.7609#show int | include line |err
    Vlan1 is down, line protocol is down
         0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored
         0 packets output, 0 bytes, 0 underruns
         0 output errors, 0 interface resets
    Vlan11 is administratively down, line protocol is down
         0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored
         0 packets output, 0 bytes, 0 underruns
         0 output errors, 0 interface resets
    Vlan99 is down, line protocol is down
         0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored
         0 packets output, 0 bytes, 0 underruns
         0 output errors, 0 interface resets

    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#show interfaces | include line |errors 
                                                                       ^
    % Invalid input detected at '^' marker.
    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#show interfaces | include line |?    

    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#show interfaces | include line | |?
                                                                        ^
    % Invalid input detected at '^' marker.
    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#show interfaces | include line | ?
      begin    Begin with the line that matches
      exclude  Exclude lines that match
      file     Save the configuration
      include  Include lines that match
      utility  A set of common unix utilities
      <cr>    
    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#show interfaces | include line |
    % Incomplete command.
    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#show interfaces | include line |errors
                                                                       ^
    % Invalid input detected at '^' marker.
    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#                                     
    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#show interfaces | include line | ?   
      begin    Begin with the line that matches
      exclude  Exclude lines that match
      file     Save the configuration
      include  Include lines that match
      utility  A set of common unix utilities
      <cr>    
    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#show interfaces | include line |?

    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#show interfaces | include line | include er$
    Thu Jan 15 22:36:24.120 GMT
    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#
    RP/0/RP0/CPU0:JA-DL-CR-1.MAN.CRS-1#show interfaces | include line           
    Thu Jan 15 22:37:05.013 GMT
    Loopback0 is up, line protocol is up
    Loopback1 is up, line protocol is up
    Loopback6 is up, line protocol is up
    Null0 is up, line protocol is up
    POS0/0/0/0 is up, line protocol is up  (APS not Configured )
    POS0/0/1/0 is up, line protocol is up  (APS not Configured )
    TenGigE0/0/4/0 is up, line protocol is up

  • Permission denied when I execute a unix command from within my java applet.

    Hi Gang,
    Forgive me if this is not the appropriate forum for this problem. I'm posting this problem on this forum since I got no answers on the other forum I posted on.
    I've written a simple java applet that runs a unix command and then displays some information. The applet compiles fine, and runs perfectly from the command line on my unix system.
    However, when I point a browser at the applet from my desktop PC I get the following error as taken from the java console:
    Exception in thread "AWT-EventQueue-2" java.security.AccessControlException: access denied (java.io.FilePermission <<ALL FILES>> execute)
    This is of course the first line in a long line of error messages. It appears that I am not able to execute a command on the unix system through my applet. I know the problem is with trying to execute a unix command since commenting it causes no error in the web browser. This is the command I'm using in java to execute the unix command:
    p = Runtime.getRuntime().exec("ps");
    Here's the html file on the unix system:
    <html>
    <head></head>
    <body>
    <appletcode=G.class height="250" width="400">
    Your browser does not support the applet tag.
    </applet>
    </body>
    </html>
    I won't list the java code since it is compiling and working on the command line. But, if you want to see it I'll provide it.
    I've done quite a bit of research on this and it seems that a great number of people have similar problems reading or executing files through java. I have yet to find a solution to this problem.
    Here are some details about my setup:
    Server:
    HP9000 running HP/UX 11.23
    Apache Web Server 2.0.35
    Java 1.5
    Desktop PC:
    Win2K Pro
    Internet Explorer 6
    Java 1.6
    If you have a solution I would be very grateful! This problem is keeping me from writing my application!
    thanks!
    kev

    Multi-posted.
    Already answered here http://forum.java.sun.com/thread.jspa?threadID=5225314&messageID=9916327#9916327

  • Permission denied when I execute a unix command from inside my Java applet.

    Hi Gang,
    Forgive me if I'm posting this to the wrong forum! I didn't get any answers on the previous forum that I posted this to.
    I've written a simple java applet that runs a unix command and then displays some information. The applet compiles fine, and runs perfectly from the command line on my unix system.
    However, when I point a browser at the applet from my desktop PC I get the following error as taken from the java console:
    Exception in thread "AWT-EventQueue-2" java.security.AccessControlException: access denied (java.io.FilePermission <<ALL FILES>> execute)
    This is of course the first line in a long line of error messages. It appears that I am not able to execute a command on the unix system through my applet. I know the problem is with trying to execute a unix command since commenting it causes no error in the web browser. This is the command I'm using in java to execute the unix command:
    p = Runtime.getRuntime().exec("ps");
    Here's the html file on the unix system:
    <html>
    <head></head>
    <body>
    <appletcode=G.class height="250" width="400">
    Your browser does not support the applet tag.
    </applet>
    </body>
    </html>
    I won't list the java code since it is compiling and working on the command line. But, if you want to see it I'll provide it.
    I've done quite a bit of research on this and it seems that a great number of people have similar problems reading or executing files through java. I have yet to find a solution to this problem.
    Here are some details about my setup:
    Server:
    HP9000 running HP/UX 11.23
    Apache Web Server 2.0.35
    Java 1.5
    Desktop PC:
    Win2K Pro
    Internet Explorer 6
    Java 1.6
    If you have a solution I would be very grateful! This problem is keeping me from writing my application!
    thanks!
    kev

    Multi-posted.
    Already answered here http://forum.java.sun.com/thread.jspa?threadID=5225314&messageID=9916327#9916327

  • How to execute a Unix Command in java

    Hi, Iam trying to execute a unix command on Sun Solaris by passing that command to a java program. How can I achieve this?
    Thanks in advance.

    Have a look at the javadoc around the Runtime.exec() method. If the command is a shell command then you might have to execute a shell as well as the command.
    For example, if you wanted to run a unix command 'ls -l > output.txt' the you might have to pass the following string into the exec() method,
    "/bin/sh ls -l > output.txt'

  • How to execute a system command with call executable in teststand 4.2.1?

    Hi All,
          how to execute a system command with "call executable" step in teststand 4.2.1?
          example as i want to quit a application.using "taskkill /f /im xxx.exe".And execute other system command(DOS).
    BR
    Johnny

    Hi, 
    I want to run netstat -an | find "8080" command from command prompt using call executable in test stand. after that i would like take the std output to local variable. 
    Attachments:
    callsettings.jpg ‏404 KB

  • Fatal error when trying to execute a dml-command with OLAP API

    Hi,
    when I created an OracleConnection using the jdbc thin driver. The connection works fine.
    But when I try to execute any dml-command with an SPLExecutor the following fatal error occurs:
    oracle.express.idl.util.OlapiException: ORA-37118: Message 37118 not found; product=RDBMS; facility=ORA
    ORA-06512: at "SYS.GENCONNECTIONINTERFACE", line 66
    ORA-06512: at line 1
    Any Suggestions ?

    Hi Priya,
    1.The entries for the initialization in the BW system are contained in the RSSDLINIT table for the DataSource/source system combination. Compare these with the entries in the ROOSPRMSC table in the OLTP system.
    2. If there are NO entries in the RSSDLINIT table in BW, use transaction RSA7 to delete the delta queue for this DataSource/BW application combination in the source system (OLTP).
    3.Once you deleted all the entries,In Infopackage scheduler option,delete all the init selections to proceed further.
    In which system u r going to do this.....Quality or production.(Better,you check with basis to delete the entries.)
    Regards
    Kumar

  • Problem in executing a unix command through java

    hi
    i'm trying to execute unix command through java
    simple shell command like "ls -l >test " but i'm not able to see the result.
    there are no error messages.
    Code is:
    import java.lang.Runtime.*;
    class ExecDemo
         public static void main(String[] args)
              Runtime r=Runtime.getRuntime();
              Process p=null;
              try
                   p=r.exec("ls -l > test");
              catch (Exception e)
                   System.out.println("Error executing nedit.");
    }can anyone help please.

    get the the inputStream of the runtime object after executing the command.
    now use the readLine() function until it becomes null.
    egs: with reference to ur code.
    InputStream is=p.getInputStream()
    while(is!=null)
    String s=is.readLine();
    if the command don't execute try giving the full path also like /sbin/ls -l

  • Execute a unix command

    How is a unix command executed in Java? What is the syntax?

    Hi,
    The best way to use a UNIX command (or another command from another operating system) is to use java.lang.Runtime class ( one of the exec method)
    It will return you a Process class which represents your UNIX command being executed.
    Once you finish with your process, you just have to destroy it using the destroy method of the Process class.
    Hope you get the picture and good luck.
    touco
    Javaholic & love Duke dollars.

  • Invoking Unix command with java stored procedure

    Hi,
    I have a perfectly working environment and now I am trying to replicate the same in another server. I have a java stored procedure which invokes the Unix command using java Runtime.exec() in my code named "run". I am sure that the code is called and the java class run is resolved in oracle as I could see that in dba_java_resolvers dictionary. But I am not sure whether the function in java is called or whether a exception is thrown. how to identify this? Could there be any thing to do with settings in oracle side? please help me.
    Thanks in advance,
    Marutha

    Hi,
    Do you get any output while running the code?
    I'm testing similar solution and if there are any errors or Oracle can't execute the program due to permissions or other issues the error information will be displayed. Also in the Java class itself you need to catch exceptions and print stack trace to standard output.
    declare
    x number;
    begin
    dbms_output.enable(1000000);
    dbms_java.set_output(1000000);
    x:=system_command.run_command('testconnect.sh');
    dbms_output.put_line('Returned value='||x);
    exception
    when others then dbms_output.put_line('Sql error='||substr(sqlerrm,1,250));
    end;
    <system_command.run_command> - replace with a call to your java stored procedure.

  • ARD and UNIX commands with outdated MAN pages. (e.g. networksetup)

    I may have read it wrongly or referred to the wrong MAN page for "networksetup", but while trying to set proxies, I realise that networkservice for the ethernet port was no longer "Built-in Ethernet" but just Ethernet (without the quotes). Took quite some time to figure that one out. Any ideas if it's just the "new" MacBooks or 10.6.4 listing differently these days? I got my multiple unix commands to work :
    networksetup -setwebproxy Ethernet proxy 3128;
    networksetup -setwebproxy AirPort proxy 3128;
    networksetup -setproxybypassdomains Ethernet 10.0.1.10 *.local 10.0.0.200 10.0.0.0/16;
    defaults write com.apple.SoftwareUpdate CatalogURL 'http://10.0.1.10:8088/index-leopard-snowleopard.merged-1.sucatalog';
    softwareupdate -i -a

    Hi
    I found this out a few weeks ago after trying for about 20-30 minutes or so. Won't be the first time manual pages were wrong or out-of-date, nor the last. Depending which OS you're running there are manual pages for utilities that don't exist any more. I remember ktrace disappearing in 10.5 yet the manual page was still available. Completely gone in 10.6.
    Tony

  • 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.

  • Sending unix command with java

    Hi! I need to terminate program from server with "Ctrl+x" command.
    How do I send this kind of command to the server?

    Uh, by sending a
    new String(new char[]{'\030'})?

Maybe you are looking for

  • HP officejet 7410 scan problem

    HP Officejet 7410 scan option was working fine till now. When I push 'Scan' botton on printer it comes up with the following message"You need to install or run HP software for this feature". Other functions work ok. Any suggestions woudl be appreciat

  • Firefox not closing the first two tabs... Is there a solution ?

    Since this morning I'm not able to quit the first two tabs in firefox... It close the page but display an empty tab instead. Here's a screenshot : http://i.imgur.com/yGAP7Hn.gif Anyone experiencing the same issue ? Is there any solutions (in about:co

  • Who�s starting the program sendmail ?

    Who is executing the program sendmail on Solaris 10 ? Every time It�s made shutdown on the server, the program sendmail is started. But I don�t find who�s starting this program. The process on the server: smmsp 504 1 0 10:29:13 ? 0:00 /usr/lib/sendma

  • Monitoring using headphones

    what's up yall? i have a problem that seems simple but can't figure it out. i'm using apogee's rosetta 800 with logic. the rosetta has 8 ins/outs which are being used with a mackie 1202. outputs 1&2 of rosetta are on lines 9/10 of mackie and the alt

  • Capturing to Internal Drive

    Okay, I've read about the issues surrounding capturing to your boot drive, but I'm still confused. I got a new G5 and had a second drive installed. I want to capture to this drive, but it looks like it's lumped with the boot drive? When I look at the