4

Is it possible in unix/bash to pipe output from two commands into another?

I tried running the following command, which successfully ran both commands, but the first was piped to stdout and the second was piped to less.

$ grep 40515575 * && zgrep 40515575 * | less
  • 2
    You can group the commands: { grep 40515575 * && zgrep 40515575 *; } | less. BTW, it seems that you instead want: { grep 40515575 *; zgrep 40515575 *; } | less – devnull May 5 '14 at 9:24
  • @devnull How does your method of {} and ; differ from edvinas.me answer? Or is it just two different ways of saying the same thing? – Svish May 5 '14 at 9:58
  • 4
    Grouping commands does not create a subshell unlike saying ( command ). Secondly, command1 && command2 implies that command2 would be executed only if command1 exited with a return code of 0. On the other hand, command1; command2; implies that both commands would be executed. – devnull May 5 '14 at 10:10
4

Try this instead:

$ ( grep 40515575 * && zgrep 40515575 * ) | less
  • Looks like that worked! – Svish May 5 '14 at 9:57
  • 1
    I prefer @devnull solution : { grep 40515575 *; zgrep 40515575 *; } | less because it doesn't need to invoke a subshell, and it always does both grep (even if the first one didn't find "40515575" in any of the files). Yours (and the OP's) would miss any "40515575" if they are only present in compressed files, and not regular ones, as the first grep would then return "false". – Olivier Dulac May 5 '14 at 13:10
  • Changing && with || would fix one of the issues though, wouldn't it? Anyways, no clue what a subshell is or why I should avoid it... :p – Svish May 5 '14 at 13:21
  • @Svish: grep 40515575 * && zgrep 40515575 * runs the second command (zgrep) ONLY if the first succeeds (i.e. finds something). On the other hand grep 40515575 * || zgrep 40515575 * runs the second command ONLY if the first FAILS (i.e. does not find anything). If you want the second command to run whether or not the first succeeds, use a semicolon. – Gordon Davisson May 7 '14 at 1:06
0

Depending on the system, you may find that 'less' is capable or recognising many different types of files, such as gzip and bzip2 compressed files.

Perhaps what you really want to say is this:

less * | grep 40515575 | less

Its helpful to remember that in this case, the initial 'less' acts like 'cat', as its output is not to a TTY.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.