Wednesday, May 16, 2007

Customizing your Shell Prompt

I do a lot of work from the command line. This involves both Linux and Windows. The BASH shell is very good and much better than the Windows cmd.exe. Microsoft has finally developed a much better shell called PowerShell (which will be the subject of a future post).

In both shells I find the prompt lacking a bit. The BASH shell only shows you the name of the lowest level directory you are in (i.e. if you are in /work/stuff/more/stuff it only shows "stuff"). The default windows prompts show you the entire path, but if the path is really long then you have only a couple of characters on the line before the command you are typing wraps around. Here is how to fix this problem with both the BASH shell and PowerShell...

I want a prompt that looks like this:
user@machine | /work/stuff/more/stuff
:: Type Command Here

This gives me the full path and I still have a full line to type my command. Also when looking back at previous commands I can see what directory they were executed in.

BASH
For the BASH shell the prompt text can be controlled by the PS1 envrionment variable. For a very good overview see this webpage or this webpage. To accomplish the above I have set my PS1 variable in the .bash_profile file to:

PS1="\e[33;1m\u@\\h | \e[34;1m\w \n\e[37;1m::"

This gives the user name in yellow, the path in blue, and the command text in yellow.

PowerShell
For PowerShell the prompt text is controlled by creating a function in your PowerShell profile file called prompt. The profile file does not exist by default, but PowerShell checks for it on start up. This file should be created as :
C:\Documents and Settings\\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

Here is my prompt function:
########################################################
# Prompt
function prompt {
$d = pwd
$u = get-item Env:\USERNAME
$u = $u.value
$c = get-item Env:\COMPUTERNAME
$c = $c.value
$s = "$u@$c | "
$color = "Green"
write-host $s -ForegroundColor "Yellow" -NoNewLine
write-host $d -ForegroundColor "Green"
$promptText = "::";
$title = (get-location).Path;

write-host $promptText -NoNewLine -ForegroundColor "Yellow"
$host.UI.RawUI.WindowTitle = $title;

return " "
}
########################################################

This gives the user name in yellow and the path in green (the default PowerShell background is blue). The command text still ends up being white.

No comments: