home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Unix Power ToolsUnix Power ToolsSearch this book

4.4. Simulating Dynamic Prompts

Some shells don't have the special "dynamic" prompt-setting sequences shown in Section 4.3. If you still want a dynamic prompt, you probably can simulate one. Both ksh and bash will expand variables (like $PWD), do command substitution (to run a command like 'date'), and do arithmetic as they print the prompt. So, for example, you can put single quotes around the prompt string to prevent interpretation of these items as the prompt is stored. When the prompt string is interpreted, the current values will be put into each prompt. (zsh gives control over whether this happens as a prompt is printed. If you want it to happen, put the command setopt prompt_subst (Section 28.14) in your .zshrc file (Section 3.3).)

The following prompt stores the $PWD parameter to give the current directory, followed by a backquoted date command. The argument to date is a format string; because the format string is inside single quotes, I've used nested double quotes around it. Because it's in single quotes, it's stored verbatim -- and the shell gets the latest values from date and $PWD each time a prompt is printed. Try this prompt, then cd around the filesystem a bit:

PS1='`date "+%D %T"` $PWD $ '

That prompt prints a lot of text. If you want all of it, think about a multiline prompt (Section 4.7). Or you could write a simple shell function (Section 29.11) named, say, do_prompt:

# for bash
function do_prompt {
   date=`date '+%D %T'`
   dir=`echo $PWD | sed "s@$HOME@~@"`
   echo "$date $dir"
   unset date dir
}

# for ksh
do_prompt( ) {
   date=`date '+%D %T'`
   dir=`echo $PWD | sed "s@$HOME@~@"`
   echo "$date $dir"
   unset date dir
}

and use its output in your prompt:

PS1='`do_prompt` $ '    ...for sh-type shells

The original C shell does almost no interpretation inside its prompt variable. You can work around this by writing a shell alias (Section 29.2) named something like setprompt ( (Section 4.14) that resets the prompt variable after you do something like changing your current directory. Then, every time csh needs to print a prompt, it uses the latest value of prompt, as stored by the most recent run of setprompt. (Original Bourne shell users, see Section 4.15 for a similar trick.)

--JP, TOR, and SJC



Library Navigation Links

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