Chapter 12. End-User Tasks as Shell Scripts

You have seen a lot of smaller scripts and syntax up to now. Our examples have, of necessity, been small in scale and scope. Now we would like to show you a few larger (though not large) examples. They are meant to give you useful, real-world examples of actual uses of shell scripts beyond just system administration tasks. We hope you find them useful or usable. More than that, we hope you learn something about bash by reading through them and maybe trying them yourself or even tweaking them for your own use.

12.1 Starting Simple by Printing Dashes

Problem

You want a simple script that prints a line of dashes.

Solution

Printing a line of dashes with a simple command might sound easy—and it is. But as soon as you think you’ve got a simple script, it begins to grow. What about varying the length of the line of dashes? What about changing the character from a dash to a user-supplied character? Do you see how easily feature creep occurs? Can we write a simple script that takes those extensions into account without getting too complex?

Consider the script in Example 12-1.

Example 12-1. ch12/dash
#!/usr/bin/env bash
# cookbook filename: dash
# dash - print a line of dashes
# options: # how many (default 72)
#         -c X use char X instead of dashes
#
function usagexit ( )
{
    printf "usage: %s [-c X] [#]\n" ${0##*/}  1
    exit 2
} >&2

LEN=72                                        
CHAR

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.