## 4.15. External Commands Send Signals to Set Variables

The Bourne shell's trap (Section 35.17) will run one or more commands when the shell gets a signal (Section 24.10) (usually, from the kill command). The shell will run any command, including commands that set shell variables. For instance, the shell could reread a configuration file; Section 24.13 shows that. Or it could set a new PS1 prompt variable that's updated any time an external command (like another shell script or a cron job (Section 25.2)) sends the shell a signal. There are lots of possibilities.

This trick takes over signal 5 (SIGTRAP), which usually isn't used. When the shell gets signal 5, a trap runs a command to get the date and time, then resets the prompt. A background (Section 23.2) job springs this trap once a minute. So, every minute, after you type any command, your prompt will change.

You can use any command's output in your prompt (possibly with some editing, probably with sed (Section 34.1) or expr (Section 36.21)): count the number of users, show the load average (Section 26.4), whatever. Newer shells, like bash, can run a command in backquotes (Section 28.14) each time the prompt is displayed -- Section 4.10 has an example. But, to have an external command update a shell variable at any random time, this trap trick is still the best.

Go to http://examples.oreilly.com/upt3 for more information on: date- prompt.sh

Now on to the specific example of putting date and time in the old Bourne shell's prompt. If your system's date command doesn't understand date formats (like `+%a`), get one that does. Put these lines in your .profile file (or just type them in at a Bourne shell prompt):

>     # Put date and time in prompt; update every 60 seconds:
>     trap 'PS1=`date "+%a %D %H:%M%n"`\
>     $\ ' 5
>     while :

`:` Section 36.6

>     do
>         sleep 60
>         kill -5 $$
>     done &
>     promptpid=$!

Now, every minute after you type a command, your prompt will change:

>     Thu 06/20/02 02:33
>     $ cc bigprog.c
>     undefined symbol                first referenced in file
>     xputc                               bigprog.o
>     ld fatal: Symbol referencing errors.
>     Thu 06/20/02 02:34
>     $ ls
>     bigprog.c
>     bigprog.o
>     Thu 06/20/02 02:35
>     $

The prompt format is up to you. This example makes a two-line prompt (Section 3.7) with backslashes (`\`) to protect the newline and space from the trap; a single-line prompt might be easier to design. The manual page for date lists what you can put in the prompt.

This setup starts a while loop (Section 35.15) in the background. The promptpid variable holds the process ID number (Section 24.3) of the background shell. Before you log out, you should kill (Section 24.12) the loop. You can type the command:

>     kill $promptpid

at a prompt or put it in a file that's executed when you log out (Section 4.18).

--JP and SJC

Copyright © 2003 O'Reilly & Associates. All rights reserved.