O'Reilly logo

bash Cookbook by Cameron Newham, JP Vossen, Carl Albing

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

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.

Starting Simple by Printing Dashes

Problem

To print 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?

Solution

Consider this script:

 1 #!/usr/bin/env bash
 2 # cookbook filename: dash
 3 # dash - print a line of dashes
 4 # options: # how many (default 72)
 5 #         -c X use char X instead of dashes
 6 #
 7 function usagexit ( )
 8 {
 9     printf "usage: %s [-c X] [#]\n" $(basename $0)
10     exit 2
11 } >&2
12 LEN=72
13 CHAR='-'
14 while (( $# > 0 ))
15 do
16     case $1 in
17     [0-9]*) LEN=$1;;
18     -c)shift 19 CHAR=$1;; 20 *) usagexit;; 21 esac 22 shift 23 done 24 if (( LEN > 4096 )) 25 then 26 echo "too large" ...

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