Compare command outputs with process substitution

Every sysadmin knows the situation, if he has to compare the output of some commands. Most of us save the output of the commands in a temporary file, compares these files with the diff binary and afterwards delete the temporary files. In this blog post I’ll show you the usage of process substitution to get the differences of commands without creating temporary files.

Situation

We’ve got two files with a list of users. Now we would like to search for usernames like user,  sort the output, get the unique entries and compare the outputs without creating a temporary file.

user1
user5
user1
docker
confirm
user1
user4
user1
docker
ansible

Solution with process substitution

There’s a nice feature called process substitution, which can be used to compare the output of programs directly.

<(command)

In combination with the diff binary.

diff <(command1) <(command2)

And here’s the final solution with the combination of the diff binary and process substitution.

diff <(grep user list1.txt|sort|uniq) <(grep user list2.txt|sort|uniq)
4d3
< user5
5a5
> user9

Conclusion

Process substitution is also a useful feature for other use cases like avoiding subshells. And it isn’t only a bash feature, it can be used with other shells like zsh or ksh as well. Just check out this page, if you like to know more about process substitution.

One Comment

  • wings io Reply

    Most of us save the output of the commands in a temporary file, compares these files with the diff binary and afterwards delete the temporary files.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.