Unix Concepts   «Prev 

Defining Complex Unix Prompt

The prompts you have seen up until now have included only literal characters. Prompts also can include shell features such as variables and the history number, the command number tracked by the history feature.

Including the history number

When the history feature is turned on, each command is assigned a consecutive number so you can refer to previous commands. Numbering your commands in order makes it easier to track them. For example:
1 % cd
2 % cp old new
3 % rm new
4 %
To include the history number, use the characters \! in the prompt definition. Here is a sample command and the result:
% set prompt="\! %" 
15 %

This example assumes that the set command was the 14th command of my session. The next command will be number 15, and the prompt will add on to this number as new commands are entered. The ! character produces the command number, but the ! must have a backslash (\) before it. Without the \, the prompt definition is permanently set to the history number of this particular set prompt command and will not increase.


Including your current directory

If you display your current directory in your prompt, you can avoid entering the pwd command all the time. One way to avoid updating the prompt every time you change directories isto create an alias to the cd command:
					
% alias cd 'cd \!* ; 
set prompt="$cwd % "'
The next time I enter cd, the prompt includes my current directory. The prompt will change with every use of cd. For example:
					
% cd
/u/danielg %

Let us examine this complex alias one piece at a time. First, recognize that the alias consists of two commands: the cd command, then the command separator (;), then the following prompt definition:
set prompt="$cwd % " 

The C shell stores your current working directory in the cwd shell variable. To access the value of any variable, put a $ before the variable name, as in $cwd. Finally, double quotes are required here, instead of single quotes. Double quotes allow the shell to interpret variables, which is what you want to do in this case. Note the first part of the alias:
cd \!*
In aliases, \!* stands for all arguments of the current command, which is cd in this case. The \!* causes the alias to work whether you use the plain cd command (without an argument) or whether you use the cd directory form. The whole alias definition is enclosed in single quotes (') so that it is interpreted as one argument.
In plain English, the entire alias definition reads as follows: “Run the cd command along with its arguments. Then set the prompt to the name of the directory you just went to.”