An alternative to the pipe (in bash/ksh)
Nov. 6th, 2010 02:07 am![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
![[community profile]](https://www.dreamwidth.org/img/silk/identity/community.png)
Most people in here will probably know how to pipe output from one command to another:
However, what if
It turns out that you can do this in bash and ksh by using the
This will execute
At first this doesn't seem too useful, but this means that you can do nifty things like this:
Which will sort filea.txt and fileb.txt, and then diff the outputs - all without writing a single file.
Note that if the subshells require user input, this isn't going to work, so you can't use this to capture user input and pass it to a script which would otherwise require a filename. However, as long as this isn't the case, everything should work smoothly.
[edit: Oh, and I should mention that,unlike piping, you can execute several commands in the subshell. For example:
This also demonstrates how both the subshell and the main process run simultaneously; the output is "sseneehw", followed by a delay of 2 seconds, followed by "gralb".]
[edit 2: See this comment for an example of how to run multiple commands via piping!]
command 1 | command2
However, what if
command2
doesn't allow reading from standard input, and only supports filenames? How can you do this without writing to a file?It turns out that you can do this in bash and ksh by using the
<(command)
syntax. For example, the above command can be written:command2 <(command1)
This will execute
command1
in a subshell, and at the same time, call command2
with a file descriptor looking something like /dev/fd/63
. When command2
reads from that, it'll get the output of command1
.At first this doesn't seem too useful, but this means that you can do nifty things like this:
diff -u <(sort filea.txt) <(sort fileb.txt)
Which will sort filea.txt and fileb.txt, and then diff the outputs - all without writing a single file.
Note that if the subshells require user input, this isn't going to work, so you can't use this to capture user input and pass it to a script which would otherwise require a filename. However, as long as this isn't the case, everything should work smoothly.
[edit: Oh, and I should mention that,
rev <(echo wheeness; sleep 2; echo blarg)
This also demonstrates how both the subshell and the main process run simultaneously; the output is "sseneehw", followed by a delay of 2 seconds, followed by "gralb".]
[edit 2: See this comment for an example of how to run multiple commands via piping!]