How can I pipe the stdout of multiple commands to a single command?
Example 1: combine and sort the output of all three echo commands:
echo zzz; echo aaa; echo kkk
desired output:
aaa
kkk
zzz
Example 2: rewrite the following so that all the commands are in a single command-line using pipes, without redirects to a temp file:
setopt > /tmp/foo; unsetopt >> /tmp/foo; set >> /tmp/foo; sort /tmp/foo
You can make it do so by using the pipe character '|'. Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on.
Using the Semicolon (;) Operator Segmenting a chain of commands with the semicolon is the most common practice when you want to run multiple commands in a terminal.
One of the most powerful shell operators is the pipe ( | ). The pipe takes output from one command and uses it as input for another. And, you're not limited to a single piped command—you can stack them as many times as you like, or until you run out of output or file descriptors.
Use parentheses ()'s to combine the commands into a single process, which will concatenate the stdout of each of them.
Example 1 (note that $
is the shell prompt):
$ (echo zzz; echo aaa; echo kkk) | sort
aaa
kkk
zzz
Example 2:
(setopt; unsetopt; set) | sort
You can use {}
for this and eliminate the need for a sub-shell as in (list)
, like so:
{ echo zzz; echo aaa; echo kkk; } | sort
We do need a whitespace character after {
and before }
. We also need the last ;
when the sequence is written on a single line.
We could also write it on multiple lines without the need for any ;
:
Example 1:
{
echo zzz
echo aaa
echo kkk
} | sort
Example 2:
{
setopt
unsetopt
set
} | sort
In Windows it would be as follow: (echo zzz & echo aaa & echo kkk) | sort
Or if it is inside a batch file it can be mono line (like sample) as well as multiline:
(
echo zzz
echo aaa
echo kkk
) | sort
Note: The original post does not mention it is only for Linux, so I added the solution for Windows command line... it is very useful when working with VHD/VHDX with diskpart inside scripts (echo diskpart_command
) instead of the echo on the same, but let there the echo
, there is also another way without echos and with >
redirector, but it is very prone to errors and much more complex to write (why use a complicated prone to errors way if exists a simple way that allways work well)... also remember %d%
gives you the actual path (very useful for not hardcoding the path of VHD/VHDX files).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With