Chapter 8. Intermediate Shell Tools II

This chapter introduces some more useful utilities that are not part of the shell but are used in so many shell scripts that you really should know about them.

Sorting is such a common task, and so useful for readability reasons, that it’s good to know about the sort command. In a similar vein, the tr command will translate or map from one character to another, or even just delete characters.

One common thread here is that these utilities are written not just as standalone commands, but also as filters that can be included in a pipeline of commands. These sorts of commands will typically take one to many filenames as parameters (or arguments), but in the absence of any filenames they will read from standard input. They also write to standard output. That combination makes it easy to connect to the commands with pipes, as in something | sort | even more.

This makes them especially useful, and avoids the clutter and confusion of a myriad of temporary files.

8.1 Sorting Your Output

Problem

You would like output in a sorted order, but you don’t want to write (yet again) a custom sort function for your program or shell script. Hasn’t this been done already?

Solution

Use the sort utility. You can sort one or more files by putting the filenames on the command line:

sort file1.txt file2.txt myotherfile.xyz

With no filenames on the command line, sort will read from standard input, so you can pipe the output from a previous command into sort:

Get bash Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.