Chapter 35. Shell Programming for the Uninitiated

Writing a Simple Shell Program

A shell script need be no more than a command line saved in a file. For example, let’s assume that you’d like a compact list of all the users who are currently logged in on the system.

A command like this might do the trick:

% who | cut -c1-8 | sort -u | pr -l1 -8 -w78 -t

A list of logged-in users should come out in columns, looking something like this:

abraham  appleton biscuit  charlie  charlott fizzie   howard   howie
hstern   jerry    kosmo    linda    ocshner  peterson root     ross
sutton   yuppie

We used four Unix commands joined with pipes:

  1. who (Section 2.8) gives a list of all users.

  2. cut -c1-8 (Section 21.14) outputs columns 1-8 of the who output — the usernames.

  3. sort -u (Section 22.6) puts names in order and takes out names of users who are logged on more than once.

  4. pr -l1 -8 -w78 -t (Section 21.15, Section 45.6) takes the list of usernames, one per line, and makes it into 8 columns on 78-character-wide lines. (The -l1 is the lowercase letter L followed by the digit 1.)

If you wanted to do this frequently, wouldn’t it be better if all you had to do was type something like:

% loggedin

to get the same result? Here’s how:

  1. Start a text editor on a new file named loggedin.

  2. If your system supports the special #! notation (Section 36.2) (and it probably does), the first line of the script file should be:

    #!/bin/sh

    Otherwise, leave the first line blank. (When the first line of a script is blank, most shells will start a Bourne shell to ...

Get Unix Power Tools, 3rd 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.