UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 7.12 External Commands Send Signals to Set Variables Chapter 7
Setting Your Shell Prompt
Next: II. Let the Computer Do the Dirty Work
 

7.13 Pre-Prompt Commands in bash

bash can run a UNIX command, or multiple commands, before it prints every prompt. This command does not have to set the prompt; it just happens to be run before each prompt is printed. The command could do some system checking, reset shell variables, or almost anything that you could type at a shell prompt. Store the command(s) in the PROMPT_COMMAND shell variable. If the commands run slowly, though, they'll delay your prompt.

Here's a silly example that I used to have in my bash setup file (2.2):

IFS 

set smiley 



shift $# 


PROMPT_COMMAND='
# Save old $IFS; set IFS to tab:
OIFS="$IFS"; IFS="   "
# Put x in $1, face in $2, explanation[s] in $3[, $4, ...]:
set x `smiley`
# Put face into $face and explanation(s) into $explan:
face="$2"; shift 2; explan="$*"
# Restore shell environment:
shift $#; IFS="$OIFS"'

# Prompt I use (includes the latest $face):
PS1='\u@\h $face '

The first part is a series of shell commands that are stored in the PROMPT_COMMAND variable; they're surrounded by a pair of single quotes (' '), one on the first line (after the =) and the other after IFS is reset. That series of commands is executed before every prompt. It sets two shell variables, $face and $explan, with new values before each prompt is set. The prompt is set on the last line; it includes the value of $face.

Here's what my screen looked like with this ridiculous setup. Notice that the prompt keeps changing as the PROMPT_COMMAND resets $face and $explan. If I wanted the explanation of a face I saw as I went along, I could type echo <">$explan<">:

jerry@ruby :-{) echo "$explan"
normal smiling face with a moustache
jerry@ruby +<||-) vi proj.cc
   ...
jerry@ruby :-O echo "$explan"
Mr. Bill
        Wow!
        ohh, big mouth, Mick Jagger
        uh oh
jerry@ruby :-)   < g++ -Wall proj.cc
   ... 

(It was even more useless than psychoanalyze-pinhead (32.13), but it was fun while it lasted.) Seriously now, I'll say again: PROMPT_COMMAND does not have to be used to set a prompt. You can use it to run any commands. If the commands in PROMPT_COMMAND write to standard output or standard error, you'll see that text before the prompt.

- JP


Previous: 7.12 External Commands Send Signals to Set Variables UNIX Power ToolsNext: II. Let the Computer Do the Dirty Work
7.12 External Commands Send Signals to Set Variables Book IndexII. Let the Computer Do the Dirty Work

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System