7.12 External Commands Send Signals to Set VariablesThe Bourne shell's trap (44.12 ) will run one or more commands when the shell gets a signal (38.8 ) (usually, from the kill command). The shell will run any command, including commands that set shell variables. For instance, the shell could re-read a configuration file; article 38.11 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 (40.12 ) ) sends the shell a signal. There are lots of possibilities. This trick takes over signal 5, 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 (1.27 ) job springs this trap once a minute. So, every minute, after you type any command, your prompt will change. You could run any command: count the number of users, show the load average (39.7 ) , whatever. And newer shells, like bash , can run a command in backquotes (9.16 ) each time the prompt is displayed - article 7.8 has an example. But, to have an external command update a shell variable at any random time, this trap trick is still the best. 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 # Put date and time in prompt; update every 60 seconds: trap 'PS1=`date "+%a %D %H:%M%n"`\ $\ ' 5 while : do sleep 60 kill -5 $$ done & promptpid=$! Now, every minute after you type a command, your prompt will change: Mon 02/17/92 08:59 $ The prompt format is up to you.
This example makes a
two-line prompt (7.5
)
,
with backslashes ( This setup starts a while loop (44.10 ) in the background. The promptpid variable holds the process ID number (38.3 ) of the background shell. Before you log out, you should kill (38.10 ) 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 (3.2 ) . - |
|