O'Reilly logo

Shell Scripting: Expert Recipes for Linux, Bash, and More by Steve Parker

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

paste

The paste command is the opposite of cut; it pastes multiple files together, separated (by default) by tabs. This is not to be confused with the terms “cut” and “paste” when used in the context of a graphical user environment (GUI). The paste command creates tabular data from multiple files, so given three files it will put them together in three columns, the first from file1, the middle column from file2, and the final column from file3. It can take as input as many files as you like.

This script takes an input file hosts, which lists a set of hosts and uses that to store the IP and Ethernet address of each host. To ensure that the || structure fails if the grep or getent commands fail, the pipefail shell option is set. The script is therefore sure to write exactly one line to both $IPS and to $ETHERS, whether it succeeds or fails. This ensures that the files will be in step when pasted together. When pipefail is set, any failure anywhere in the pipeline causes the whole pipeline to fail. By default, the return value of the pipeline is the return value of the final command in that pipeline. This would mean that the success of getent hosts | cut is determined by the return code of cut, which pretty much always returns 0 to indicate success.

cat hosts
localhost
plug
declan
atomic
broken
goldie
elvis
$ cat /etc/ethers
0a:00:27:00:00:00 plug
01:00:3a:10:21:fe declan
71:1f:04:e3:1b:13 atomic
01:01:8d:07:3a:ea goldie
01:01:31:09:2a:f2 elvis
$ cat gethosts.sh #!/bin/bash HOSTS=hosts ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required