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 ():

 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 (), 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