Bash function/script to execute multiple commands on same output

Occasionally, I come across the need to pass the output of a single command to multiple others (without piping each to the next), so today, I wrote a [very] simple Bash script to accomplish the task.  Piping the output of a command to `tree' is much like piping it to `tee', except `tree' allows you to execute multiple commands on the same output, rather than only writing to log files:
#!/bin/bash
# tree -- pipes the output of one command to >= 1 other
# Usage: command | tree 'command 1' 'command 2'
doc=$( cat - )
for arg in "$@"; do
bash -c "${arg}" <<EOF
${doc}
EOF
done
An example of its usage:
$ echo -e "1 2 3\n4 5 6" | tree 'grep 1' 'grep 4' "grep 1 | tee grep.log | awk '{print \$2}'"
1 2 3
4 5 6
2
$ cat grep.log
1 2 3
Though not elaborate, the script gets the job done.
Last edited by deltaecho (2009-03-10 20:34:01)

Xyne wrote:
You could always call it "the Ukrainian Pipe"
(if you can't laugh at this, you either need to loosen up or make a point to follow (annual) current events)
That was a good one

Similar Messages

  • Executing multiple commands with sudo fails

    Hi,
    We're having trouble with sudo and bash.  When we want to execute multiple commands and there are spaces, the commands don't run.  Here's an example of what works:
    [root@erpapp1-prod ~]# sudo -i -u oracle bash -c 'ls;pwd'
    In this case, I get a listing of the files in /home/oracle followed by the current directory of /home/oracle.
    Here's an example of what DOESN'T work:
    [root@erpapp1-prod ~]# sudo -i -u oracle bash -c 'ls; pwd'
    Notice the space before "pwd".  In this case, all I get is the listing of files in /home/oracle.
    Caveat:  I'm a real beginner with Linux.  I've compared many of the files (/home/oracle/.bash_profile, /home/oracle/.bashrc, /etc/bashrc, /etc/profile) from this server to another where we don't have issues and, other than some logic being in different order, don't see much of a difference.  Again, very beginner here.
    Any ideas?  Thanks!
    Todd

    What shows up as a space may not necessarily be a space. For instance, it could be some control character like a newline, which might interfere with the execution. For example:
    $ test=`echo -e "test;\ntest"`
    $ echo $test
    test; test
    $ echo "$test"
    test;
    test
    Here is another example:
    # test=`echo -e "ls;\npwd"`
    # su - oracle -c "$test"
    oradiag_oracle
    /home/oracle
    # su - oracle -c $test
    oradiag_oracle
    I cannot guess how you construct the command list. Perhaps the problem is a text files that was created under Windows and copied as binary to Linux, or a shell script using a different IFS environment variable, etc.
    Personally I would use a different approach. From a security standpoint it is a bad idea to use passwords at the command prompt because every user can see them using the ps -ef  output.

  • Using ProcessBuilder to execute multiple commands.

    I am having issues getting ProcessBuilder to execute multiple commands in windows.
    As an example I would like to execute "dir /w" fallowed by "java.exe some.App arg1 arg2".
    I can accomplish this from the command line by using "&".
    Example: dir /w & java.exe some.App arg1 arg2 Or: dir /w & dir /c"
    For internal commands (i.e. dir and cd) I know that commands in the array being passed to ProcessBuilder must be formatted like {"dir /w", "dir /c"}
    see post: [http://www.java-tips.org/java-se-tips/java.util/from-runtime.exec-to-processbuilder.html]
    Here is an example of one of the many things I have tried:
    {code}
    String[] commands = new String[]{"dir /w", "&", "java.exe", "some.App", "arg1", "arg2"};
    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.start();
    {code}
    Any other ideas / what am I doing wrong?
    Edited by: brianjbrady on May 7, 2009 4:49 PM
    Edited by: brianjbrady on May 7, 2009 4:50 PM

    brianjbrady wrote:
    You can run dir all day long without using cmd.exe. Try it. It works for me.Perhaps you have cygwin in your path.
    How are you running dir out of interest (and don't say with a DOS window ;)
    import java.io.*;
    import java.util.Arrays;
    public class Main {
        public static void main(String... args) throws IOException {
            run("dir");
            run("dir.exe");
            run("cmd", "/c", "dir");
            run("c:\\cygwin\\bin\\dir");
        private static void run(String... command) throws IOException {
            try {
                ProcessBuilder pb = new ProcessBuilder(command);
                pb.redirectErrorStream(true);
                Process p = pb.start();
                InputStream is = p.getInputStream();
                System.out.println("\nCommand " + Arrays.asList(command) + " reported");
                int b;
                while ((b = is.read()) >= 0)
                    System.out.write(b);
                is.close();
                p.destroy();
            } catch (IOException e) {
                System.err.println("\nCommand " + Arrays.asList(command) + " reported " + e);
    }Prints
    Command [dir] reported java.io.IOException: Cannot run program "dir": CreateProcess error=2, The system cannot find the file specified
    Command [dir.exe] reported java.io.IOException: Cannot run program "dir.exe": CreateProcess error=2, The system cannot find the file specified
    Command [cmd, /c, dir] reported
    Volume in drive D is Work Disk
    Volume Serial Number is AC0B-0757
    Directory of D:\dev\scratch
    26/12/2008  22:15    <DIR>          .
    26/12/2008  22:15    <DIR>          ..
    03/09/2007  21:45    <DIR>          classes
    26/08/2008  20:14            65,280 mynamedpipe
    23/11/2008  11:37           201,354 name.ppt.txt
    24/10/2008  20:00           201,354 race.txt
    05/11/2008  23:17         6,193,334 record.csv
    08/01/2009  16:44               704 scratch.iml
    27/12/2008  12:29            21,576 scratch.ipr
    08/05/2009  20:02            53,258 scratch.iws
    28/04/2009  21:34    <DIR>          src
    07/12/2008  11:44               101 test.txt
                   8 File(s)      6,736,961 bytes
                   4 Dir(s)  32,506,023,936 bytes free
    Command [c:\cygwin\bin\dir] reported
    classes      name.ppt.txt  record.csv     scratch.ipr  src
    mynamedpipe  race.txt        scratch.iml     scratch.iws  test.txt

  • Executing multiple commands

    how to execute multiple commands through java programming .I tried with the code
    Process pro=Runtime.getRuntime().exec("cmd /c cd C:\\Symbian\\Carbide\\MyXmlParserWeb\\group\\s60_3rd");
              pro.waitFor();
              BufferedReader reader=new BufferedReader(new InputStreamReader(pro.getInputStream()));
              String line=reader.readLine();
              while(line!=null)
              System.out.println(line);
              line=reader.readLine();
              for(int i=0;i<2;i++){
                   try {
                        Thread.sleep(500);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              Process pro4=Runtime.getRuntime().exec("bldmake clean");
              pro.waitFor();
              BufferedReader reader4=new BufferedReader(new InputStreamReader(pro4.getInputStream()));
              String line4=reader4.readLine();
              while(line4!=null)
              System.out.println(line4);
              line4=reader4.readLine();
              for(int i=0;i<2;i++){
                   try {
                        Thread.sleep(500);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              Process pro1=Runtime.getRuntime().exec("bldmake bldfiles");
              pro1.waitFor();
              BufferedReader reader1=new BufferedReader(new InputStreamReader(pro1.getInputStream()));
              String line1=reader1.readLine();
              while(line1!=null)
              System.out.println(line1);
              line1=reader.readLine();
              for(int i=0;i<2;i++){
                   try {
                        Thread.sleep(500);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              }

    class MainClass extends Thread {
         InputStream is;
         String type;
         OutputStream os;
         MainClass(InputStream is, String type)
         this(is, type, null);
         MainClass(InputStream is, String type, OutputStream redirect)
         this.is = is;
         this.type = type;
         this.os = redirect;
         public void run()
         try
         PrintWriter pw = null;
         if (os != null)
         pw = new PrintWriter(os);
         InputStreamReader isr = new InputStreamReader(is);
         BufferedReader br = new BufferedReader(isr);
         String line=null;
         while ( (line = br.readLine()) != null)
         if (pw != null)
         pw.println(line);
         System.out.println(type + ">" + line);
         if (pw != null)
         pw.flush();
         } catch (IOException ioe)
         ioe.printStackTrace();
         public static void main(String args[])
         if (args.length < 1)
         System.out.println("USAGE java GoodWinRedirect <outputfile>");
         System.exit(1);
         try
         FileOutputStream fos = new FileOutputStream(args[0]);
         Runtime rt = Runtime.getRuntime();
         Process proc = rt.exec("cmd.exe");
         // any error message?
         MainClass errorGobbler = new
         MainClass(proc.getErrorStream(), "ERROR");
         // any output?
         MainClass outputGobbler = new
         MainClass(proc.getInputStream(), "output", fos);
         // kick them off
         errorGobbler.start();
         outputGobbler.start();
         // any error???
         int exitVal = proc.waitFor();
         System.out.println("ExitValue: " + exitVal);
         fos.flush();
         fos.close();
         } catch (Throwable t)
         t.printStackTrace();
    i have modified the code again.but still no result.....

  • Script to execute multiple select query

    Hi,
    What is the script to execute 5 ~ 15 select statement which will call pl sql functions simultaneously/concurrently and run it in sqlplus . I need to know the time taken by the queries to execute when there are multiple request calling the select statement.
    Thanks.

    I guess you can create 15 different shell scripts (on the server) which in turn call sqlplus and then call the 15 scripts in the background mode. Assuming your server is Unix, put an ampersand after your each shell script call to run in background.

  • Executing Multiple Commands (Runtime Class)

    granting that Runtime class could execute a command.
    Is it possible to execute a list of commands in
    just one process, for example "cd\javasdk" followed by "dir *.java".
    Any idea to do this?
    Thnx in advance.

    Execute either a script (a batch file) containing all commands or execute the command interpreter (sh, bash, cmd.exe) and feed it through its standard input.

  • Error when executing multiple scenarios with same ProgramID for RFC-JDBC

    Hi,
    I am working on the RFC-JDBC scenario.
    I see the following error in the dev_jrfc.trc file when I try to execute multiple scenarios which are using same program id (different communication channels).
    RfcException:
        message: Commit fault: com.sap.aii.af.rfc.afcommunication.RfcChannelMismatchException: Wrong Sender Agreement:The Sender agreement does not have channel CC_SAP_XXXXX configured for the functionmodule Z_XXXXX_SO_CREATE_CHANGE
        Return code: RFC_CLOSED(6)
        error group: 108
        key: RFC_ERROR_INTERNAL
    Can one program id be used for multiple scenarios? Or do we need to create a new ProgramId for each scenario.
    Any response will be highly appreciated.
    Thanks
    Shyam

    Hello Shyam,
    >>>>>>>>Do you think that I still need to create a new Program Id for each of these processes.
    You should not use same program ID for different RFC adapters. It is recommended by SAP (check FAQ's on RFC).
    Although technically you can use but it gives you unpredictable behaviour based on connection pool.

  • Execute dir command and get output

    Hi,
    Is it possible to execute a command such as dir,md or copy using a java prorgam.Plz tell me how to do this.
    Thanks a lot,
    Chamal.

    You can get that dir info from java.io.File.listFiles(), of course.
    But if you just want to run OS commands you can do it with java.lang.Runtime:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    MOD

  • Jython script to execute OS Command based on OS

    Hi,
    Could anyone help me in writing Jython script in ODI to execute a OS command (create a file with list of .csv files available in specified directory) based on the OS on which code is running?
    We have DEV and UAT are in Windows environment and Training is in Linux environment.
    I tried following http://odiexperts.com/jython-os-bug-in-windows-7/ but I am getting errors like, SyntaxError: ("no viable alternative at character '\x93'", ('<string>', 3, 13, 'os.command(r \x93 copy /r source_path dest_path\x94) \n'))
    Please help me and its urgent.
    Thanks
    MT

    Hi aetl,
    Thank you so much for your help!
    I am trying with below code
    import os
    if os._getOsType('') == 'nt':
    lv_command = 'dir /a/b > file_name.txt'
    else:
    lv_command = 'ls -l > file_name.txt'
    os.command(lv_command)
    but I am getting error as
    org.apache.bsf.BSFException: exception from Jython:
    Traceback (most recent call last):
    File "<string>", line 2, in <module>
    AttributeError: 'module' object has no attribute '_getOsType'
    Please help me.
    Regards
    MT

  • Executing multiple command lines in command prompt (windows)

    Hi,
    I am currrently using the command prompt in the windows to try to send a command to the microcontroller that is connected through TCP connection.
    I am able to use the normal cmd.exe to send the command but am unable to send all the command successfully using labview. 
    The Vi. that I am using the the system exec.vi found in labview connectivity section. 
    Basically what I want to send is "telnet A1" in the cmd.exe to establish connection to the microcontroller, followed by "FOR A1 100 GO" which will be intepreted by the microcontroller to make the necessary motion. But currently, the problem is that I can only establish connection using the system exec.vi but am unable to send the second part of the message "FOR A1 100 GO". 
    My command line i tried typing is cme.exe /K telnet A1 & FOR A1 100 GO. it seems that labview is only able to execute the first command part. Is there any other alternatives? 
    Thanks everyone for your help. 
    Solved!
    Go to Solution.

    Hi,
    Thanks for the help, the picture shows 1 of the error which state Error 56, the error occurs occasionally whenever I have used the command prompt to send a message to the microcontroller.
    Alternatively, there are times when no errors occur but my microcontroller does not move as well. It does move if I were to send the command through the cmd prompt.
    And I have attached a picture of my program as well. I am currently using Labview 2010 32bit. Thanks.
    Jh
    Attachments:
    TCP Connection.jpg ‏170 KB
    Error56.png ‏222 KB
    Picomotor_App New v3.0.vi ‏38 KB

  • Failing to execute multiple commands using psexec

    Trying to export hostname and disks that are in failed and predictive failure mode but psexec is failing to export hostname and predective failure disk information, it just giving failed disks information.
    psexec \\<<HOSTNAME>> cmd /c HOSTNAME^&"c:\Program Files (x86)\Compaq\Hpacucli\Bin\hpacucli.exe" ctrl all show config |find "Failed|Predictive Failure"

    As your command is written, the find is applied to the output of the entire
    psexec command, not just hpacucli.exe.  You need to escape the pipe character just as you did the ^&:
    ^|find.  Also, if you're trying to look for
    either "Failed" or "Predictive Failure" you're better off using the
    findstr command:
    ^| findstr /c:"Failed" /c:"Predictive Failure"

  • InDesign CS3 Scripting XML Import Multiple Images into same Text Frame

    I am having trouble importing multiple images into the same Text Frame using XML import. I imported 5 images into the text frame. However, all 5 images are laying on top of one another. Does anyone know if there is a way to have all images laying out like how Microsoft Word handles inline images, i.e., laying out next image to the right of previsous image in the same line and if there is not enough space left in the line, then wrap to next line. Thanks in advance. I understand I could use JavaScript to do post import processing, e.g, calculate the image size and place each images accordingly. But I am trying to see whether there is a way to do this without scripts.

    You can apply an object style to all anchored images by script. A text frame containing main flow should be selected.
    var doc = app.activeDocument;
    var textFrame =  app.selection[0];
    var rectangles = textFrame.texts[0].rectangles;
    if (rectangles.length > 0) {
         for (var i=0; i < rectangles.length; i++) {
              rectangles[i].appliedObjectStyle = doc.objectStyles.item("Cover");
    However, there is a better approach:
    Step 1
    Create place holders for a single "Book" element and format it as needed -- apply an object style to the cover.
    Step 2
    Import the xml file -- the placeholders are replaced with data from the 1st xml element
    Step 3
    Drag & drop the element containing all "Books" elements into the main flow -- all elements are placed and formatted the same way as in step 1.
    Finally, add a new page, click the overset text icon and autoflow text to add pages so that to fit all the text.
    Hope this helps.
    Kasyan

  • Script to Analyze multiple schemas at same time

    Hi Guys,
    I'm looking for a script by which I can analyze (estimate 25%) multiple schemas (In Oracle 9i Database) at same time. I know we can use dbms_utility but do not know, how to use for multiple schemas (around 60 schemas). I appreciate your cooperation.
    Thanks in advance.
    Regards,
    Sanjeev

    Hi Syed,
    Thanks for response,
    can u tell me how I can analyze multiple schema by using dbms_stats at same time. I would appriciate if you can send any script for me for same.
    Thanks,
    Sanjeev
    [email protected]

  • How to execute unix command from ODI Procedure

    Hi,
    I am trying to execute below unix command from ODI Procedure (Command on Target tab) but I am getting the error "java.io.IOException: Cannot run program "cd": error=2, No such file or directory" but when I try to execute the same command using OdiOSCommand, it is executing successfully. I don't want to use shell script to execute this command. Is there any specific syntax am I missing to execute this command from ODI procedure?
    cd /project3/tmt/;ls *.dmp > dmplist.lst
    Please help me on this...
    Thanks
    MT

    Hi nahlikh,
    Thank you for the reply.
    I used below command in Procedure but still getting the same error as "java.io.IOException: Cannot run program "OdiOSCommand": error=2, No such file or directory".
    OdiOSCommand "-COMMAND=cd /project3/tmt/;ls *.dmp > dmplist.lst"
    as I mentioned earlier if I use the command cd /project3/tmt/;ls *.dmp > dmplist.lst in OdiOSCommand tool it is executing successfully without any issues.
    any thoughts appreciated to get a solution for this issue.
    Thanks
    MT

  • Can we execute multiple tasks using emcli

    Hi,
    I know we can execute any task on target using emcli but just wondering if we can execute multiple command in one emcli execution,
    also does any one has any idea about how to pass the target variables in emcli command.
    Thanks,
    Ritu

    Hi Salman,
    Thanks for your reply but I do not want to use deplyoment procedured as this means for patching and provisioning related tasks,
    I want to automate the health checks using EMCLI and for that I can use submit job verb of emcli,
    I just wanted to if i have multiple command to pass to emcli,how to do that ?
    Regards,
    Ritu

Maybe you are looking for