Fun with Redirection

christine.website
7 min read
easy
Posted on 2021-09-22
Fun with Redirection

A 17 minute read.

When you're hacking in the shell or in a script, sometimes you want to change how the output of a command is routed. Today I'm gonna cover common shell redirection tips and tricks that I use every day at work and how it all works under the hood.

Let's say you're trying to capture the output of a command to a file, such as uname -av :

$ uname -av Linux shachi 5.13.15 #1-NixOS SMP Wed Sep 8 06:50:21 UTC 2021 x86_64 GNU/Linux

You could copy that to the clipboard and paste it into a file, but there is a better way thanks to the > operator:

$ uname -av > uname.txt $ cat uname.txt Linux shachi 5.13.15 #1-NixOS SMP Wed Sep 8 06:50:21 UTC 2021 x86_64 GNU/Linux

Let's say you want to run this on a few machines and put all of the output into uname.txt . You could write a shell script loop like this:

# make sure the file doesn't already exist rm -f uname.txt for host in shachi chrysalis kos-mos ontos pneuma do ssh $ host -- uname -av >> uname.txt done

Then uname.txt should look like this:

Linux shachi 5.13.15 #1-NixOS SMP Wed Sep 8 06:50:21 UTC 2021 x86_64 GNU/Linux Linux chrysalis 5.10.63 #1-NixOS SMP Wed Sep 8 06:49:02 UTC 2021 x86_64 GNU/Linux Linux kos-mos 5.10.45 #1-NixOS SMP Fri Jun 18 08:00:06 UTC 2021 x86_64 GNU/Linux Linux ontos 5.10.52 #1-NixOS SMP Tue Jul 20 14:05:59 UTC 2021 x86_64 GNU/Linux Linux pneuma 5.10.57 #1-NixOS SMP Sun Aug 8 07:05:24 UTC 2021 x86_64 GNU/Linux

Now let's say you want to extract all of the hostnames from that uname.txt . The pattern of the file seems to specify that fields are separated by spaces and the hostname seems to be the second space-separated field in each line. You can use the cut command to select that small subset from each line, and you can feed the cut command's standard input using the < operator:

$ cut -d ' ' -f 2 < uname.txt shachi chrysalis kos-mos ontos pneuma

It's worth noting that a lot of these core CLI utilities are built on the idea that they are filters, or things…
Xe
Read full article