Categories
SysOps

How to send output to multiple commands

Send output to multiple commands using tee utility and bash process substitution.

Use this method to perform a different set of operations on the same input data.

$ cat /etc/passwd | tee >(echo "All accounts: $(wc -l)") >(echo "User accounts: $(grep  -c -v "false|nologin"$)") >(echo "System accounts: $(grep -c  "false|nologin"$)") &>/dev/null
System accounts: 51
User accounts: 4
All accounts: 55

Use this method to extract interesting information from a single data source.

$ tail -f /var/log/syslog | tee >(grep --color "systemd\[.*\]:") >(grep --color "dhclient\[[0-9]*\]") &>/dev/null
Mar 16 21:33:40 milosz-XPS-13-9343 dhclient[5956]: bound to 192.168.88.240 -- renewal in 275 seconds.
Mar 16 21:33:40 milosz-XPS-13-9343 systemd[1]: Starting Network Manager Script Dispatcher Service...
Mar 16 21:33:40 milosz-XPS-13-9343 systemd[1]: Started Network Manager Script Dispatcher Service.

Use this method to extract interesting information from a single data source and store it using files.

$ tail -f /var/log/syslog | tee \
                              >(stdbuf --output=0 grep "systemd\[.*\]:" | tee /tmp/syslog-systemd.log) \
                              >(stdbuf --output=0 grep "dhclient\[[0-9]*\]:" | tee /tmp/syslog-dhclient.log) \
                              &>/dev/null
Mar 16 21:33:40 milosz-XPS-13-9343 dhclient[5956]: bound to 192.168.88.240 -- renewal in 275 seconds.
Mar 16 21:33:40 milosz-XPS-13-9343 systemd[1]: Starting Network Manager Script Dispatcher Service...
Mar 16 21:33:40 milosz-XPS-13-9343 systemd[1]: Started Network Manager Script Dispatcher Service.

Verify file contents.

$ cat /tmp/syslog-dhclient.log
Mar 16 21:33:40 milosz-XPS-13-9343 dhclient[5956]: bound to 192.168.88.240 -- renewal in 275 seconds.
$ cat /tmp/syslog-systemd.log
Mar 16 21:33:40 milosz-XPS-13-9343 systemd[1]: Starting Network Manager Script Dispatcher Service...
Mar 16 21:33:40 milosz-XPS-13-9343 systemd[1]: Started Network Manager Script Dispatcher Service.