Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Shell Prompts Customarization

News

See also

Recommended  Links

 Unix shells history Reference

Colorizing

Home directory folding
BASH Prompt Control Symbols Reference PROMPT_COMMAND String Operations in Shell        
Shell Dotfiles Command history reuse in shell Care and Feeding of Functions in Shell   bash Tips and Tricks

Humor

Etc

Introduction

Shell prompts are useful tools that simplify life of sysadmins and regular users alike, if set correctly. They became an esoteric art in bash as bash has special macros for PS1-PS4 that simplify construction of complex shells. Unfortunately not many of those esoteric examples are useful.

In any case default bash prompt is too simplistic. Even slightly more complex on such as

export PS1='\u@\h:${PWD##/*/*}${PWD#${PWD%/*/*}} # '

represents an improvement as it both current and parent directory are displayed instead of just current which is not really useful.

There is also perversions in a forms of esoteric colorizing schemes . A modest usage of colorizing schemes (for example red for root, blue for a regular users) is useful, but after that the return on investment diminishes drastically. But coloring root prompt in red helps to avoid helps to avoid costly mistakes.

So please do not spend much time inventing a new super coloring scheme for your prompts (some people have spent months trying various combination of colors for different hosts ;-).

Classic Unix prompt usually look differently for root and regular users:

regular users : username@hostname:/path $

root: hostname:/path#

The problem here is that we long path it became less usable. So a good improvement is top print path of a separate line if length of the path is longer then say 20 characters. 

Bash prompt customarization

When customizing bash prompt you can operate on three levels:

There are multiple web pages  with examples of bash prompts. Some of them are pretty educational

The most important rule in customizing bash prompt is "Not to much zeal" ;-).

Special codes

Bash provides a set of parameterless macros that can be used to customize the prompt via PS1 variable:

Bash Color Escape Codes 

The following escape codes between \[\e[  and m\] are recognized in text:

Black 0;30
Dark Gray 1;30
Blue 0;34
Light Blue 1;34
Green 0;32
Light Green 1;32
Cyan 0;36
Light Cyan 1;36
Red 0;31
Light Red 1;31
Purple 0;35
Light Purple 1;35
Brown 0;33
Yellow 1;33
Light Gray 0;37
White 1;37

For example you can try the following ;-)

export PS1="\[\e[36;1m\] \[\e[31;1m\]\u\[\033[0m\]@\[\e[34;1m\]\h\[\e[0;30m\] $ "

Bash Prompt Command

From the GNU Bash doc page: http://www.gnu.org/software/bash/manual/bashref.html
PROMPT_COMMAND
    If set, the value is interpreted as a command to execute before
    the printing of each primary prompt ($PS1).

PROMPT_COMMAND usually call a function that can contain ordinary bash statements whereas the PS1 is limited to env variables and the special characters, such as '\h' for hostname. For excample

function prompt_command {
  export PS1=$(~/bin/bash_prompt)
}
export PROMPT_COMMAND=prompt_command

Here is a relevant quote from  Bash Prompt HOWTO:

Bash provides an environment variable called PROMPT_COMMAND. The contents of this variable are executed as a regular Bash command just before Bash displays a prompt.

[21:55:01][giles@nikola:~] PS1="[\u@\h:\w]\$ "
[giles@nikola:~] PROMPT_COMMAND="date +%H%M"
2155
[giles@nikola:~] d
bin   mail
2156
[giles@nikola:~] 

What happened above was that I changed PS1 to no longer include the \t escape sequence (added in a previous section), so the time was no longer a part of the prompt. Then I used date +%H%M to display the time in a format I like better. But it appears on a different line than the prompt. Tidying this up using echo -n ... as shown below works with Bash 2.0+, but appears not to work with Bash 1.14.7: apparently the prompt is drawn in a different way, and the following method results in overlapping text.

2156
[giles@nikola:~] PROMPT_COMMAND="echo -n [$(date +%H%M)]"
[2156][giles@nikola:~]$
[2156][giles@nikola:~]$ d
bin   mail
[2157][giles@nikola:~]$ unset PROMPT_COMMAND
[giles@nikola:~]

echo -n ... controls the output of the date command and suppresses the trailing newline, allowing the prompt to appear all on one line. At the end, I used the unset command to remove the PROMPT_COMMAND environment variable.

 

Creating usable prompt  in ksh

ksh shell does not have macros for prompt so you need to script a usable prompt. For Solaris a very simplistic one might look like: 

case `/usr/xpg4/bin/id -u` in
0) PS1=" [1m [31m\$HOST:\$PWD\# [0m" ;;
*) PS1="\$LOGNAME\@\$HOST:\$PWD\$ " ;;
esac
PS2='>'
export PS1 PS2

In BASH it's simpler  generate # for root:  \$  is a bash prompt macro that expands to #  if the effective UID is 0, and to  $ otherwise. That means that equivalent Bash prompt (but without color scheme) can look something like 

PS1="\u@\h:\w\ \\$ "  

In more recent versions of bash \w also performs home directory folding. I do not know how to imitate it correctly in ksh93. Probably discipline functions can do the trick.

In more recent versions of bash \w also performs home directory folding

In ksh93 you can try to to truncate the prompt in case the current directory is a subdirectory of the home directory. ksh93 introduced ${parameter/pattern/string} substitution which later was replicated by BASH and that can be used for kind of directory folding like in the following example:

PS1='$LOGNAME\@\$HOST:\$PWD\${PWD#$OLDPWD/}$ '

Here are relevant quotes from ksh93 and bash documentation:

ksh93:

${parameter /pattern /string }

${parameter //pattern /string }

${parameter /#pattern /string }

${parameter /%pattern /string }

Expands parameter  and replaces the longest match of pattern  with the given string. Each occurrence of \n  in string is replaced by the portion of parameter  that matches the n -th sub-pattern. In the first form, only the first occurrence of pattern  is replaced. In the second form, each match for pattern  is replaced by the given string. The third form restricts the pattern match to the beginning of the string while the fourth form restricts the pattern match to the end of the string. When string  is null, the pattern  will be deleted and the / in front of string  may be omitted. When parameter  is @, *, or an array variable with subscript @ or *, the substitution operation is applied to each element in turn.

bash:

${parameter//pattern/string}
The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. In the first form, only the first match is replaced. The second form causes all matches of pattern to be replaced with string. If pattern begins with `#', it must match at the beginning of the expanded value of parameter. If pattern begins with `%', it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is `@' or `*', the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with `@' or `*', the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.

But the problem is that slashes as $HOME expansion are interpreted as substitution delimiter ("/") so the following idea does not work (Solaris example follows):  

case `/usr/xpg4/bin/id -u` in
0) PS1=" [1m [31m\$LOGNAME\@\$HOST:\${PWD/#$HOME/~}\# [0m" ;;
*) PS1="\$LOGNAME\@\$HOST:\${PWD/#$HOME/~}\$ " ;;
esac
PS2='>'
export PS1 PS2

Paradoxically the following works correctly but it just delete home directory without substitution so it not very useful:

case `/usr/xpg4/bin/id -u` in
0) PS1=" [1m [31m\$LOGNAME\@\$HOST:\${PWD#$HOME}\# [0m" ;;
*) PS1="\$LOGNAME\@\$HOST:\${PWD#$HOME}\$ " ;;
esac
PS2='>'
export PS1 PS2

Good luck with your own ksh93 shell prompt experiments and write me if you manage to do this trick in ksh93 correctly !

Dr. Nikolai Bezroukov


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Nov 25, 2006] Controlling the Size and Appearance of $PWD in BASH

Unix allows long file names, which can lead to the value of $PWD being very long. Some people (notably the default RedHat prompt) choose to use the basename of the current working directory (ie. "giles" if $PWD="/home/giles"). I like more info than that, but it's often desirable to limit the length of the directory name, and it makes the most sense to truncate on the left.

#   How many characters of the $PWD should be kept
local pwdmaxlen=30
#   Indicator that there has been directory truncation:
#trunc_symbol="<"
local trunc_symbol="..."
if [ ${#PWD} -gt $pwdmaxlen ]
then
	local pwdoffset=$(( ${#PWD} - $pwdmaxlen ))
	newPWD="${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}"
else
	newPWD=${PWD}
fi

The above code can be executed as part of PROMPT_COMMAND, and the environment variable generated (newPWD) can then be included in the prompt. Thanks to Alexander Mikhailian who rewrote the code to utilize new Bash functionality, thus speeding it up considerably.

Risto Juola (risto AT risto.net) wrote to say that he preferred to have the "~" in the $newPWD, so he wrote another version:

pwd_length=20

DIR=`pwd`

echo $DIR | grep "^$HOME" >> /dev/null

if [ $? -eq 0 ]
then
  CURRDIR=`echo $DIR | awk -F$HOME '{print $2}'`
  newPWD="~$CURRDIR"

  if [ $(echo -n $newPWD | wc -c | tr -d " ") -gt $pwd_length ]
  then
    newPWD="~/..$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
  fi
elif [ "$DIR" = "$HOME" ]
then
  newPWD="~"
elif [ $(echo -n $PWD | wc -c | tr -d " ") -gt $pwd_length ]
then
  newPWD="..$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
else
  newPWD="$(echo -n $PWD)"
fi

Relative speed: the first version takes about 0.45 seconds on an unloaded 486SX25. Risto's version takes about 0.80 to 0.95 seconds. The variation in this case is due to whether or not truncation is required.

[Nov 10, 2006] Sys Admin v15, i12 Korn Shell Nuances by Ed Schaefer and John Spurgeon

This trick works for Solaris ksh
Setting the Primary Prompt String

Using the environment variable PS1, users can create a dynamic prompt string. Here's a common example using Korn shell environmental variables:

export PS1='$LOGNAME@$SYSNAME:$PWD'":> "    
Since environmental variable PWD is dynamically set by the cd command, each time the directory changes, our PS1 displays the system name, the user name, and the current working directory.

According to Bolsky and Korn, the "ksh performs parameter expansion, arithmetic expansion, and command substitution on the value of PS1 each time before displaying the prompt". However, not all implementations of the Korn shell provide all of these features.

The version of the Korn shell we use most often performs parameter expansion but not command substitution. Under these conditions, suppose we want the prompt string to only display the last two directories of the current working directory's full pathname. For example, if PWD were:

/home/eds/jspurgeo/myentry/src 
we only want to see:
myentry/src 
Here's one way to solve the problem:
export PS1='${PWD##/*/*}${PWD#${PWD%/*/*}} >' 
To simplify the explanation, we break the solution into three pieces:

David Korn Tells All

My prompt in ksh (Score:1)
by westrick (245730) on Wednesday February 07, @10:49AM (#449478)
PS1=`uname -n`':${PWD#$OLDPWD/}$ ' Just enough info about where I am, without wasting the entire screen with $PWD.

Re Does zsh have equivalent to $PROMPT_COMMAND

> 	The only feature of bash i miss in zsh is the variable
> $PROMPT_COMMAND if set in .bashrc everytime you login for the entire
> session the command defined as the variable, is executed before each
> prompt.

Zsh does not have a $PROMPT_COMMAND variable, AFAIK. Instead, you can
define the precmd _function_ which is executed before each prompt.
Other special functions are listed in the zshmisc(1) man page.

Using a function for this is more logical than using a variable, IMHO.

[Nov 24, 2004] Re sudo and shell prompt

You should be able to set the SUDO_PS1 environment variable
and have a custom prompt for your "sudo bash" shells.

Of course, a big reason to use sudo is to _avoid_ using a root
shell, but to each his own.

- todd

[Nov 24, 2004] Bash Prompt HOWTO. Good description of prompt command and its usage in 'super-complex" shell prompts:

4.1. PROMPT_COMMAND

Bash provides an environment variable called PROMPT_COMMAND. The contents of this variable are executed as a regular Bash command just before Bash displays a prompt.

[21:55:01][giles@nikola:~] PS1="[\u@\h:\w]\$ "
[giles@nikola:~] PROMPT_COMMAND="date +%H%M"
2155
[giles@nikola:~] d
bin   mail
2156
[giles@nikola:~] 

What happened above was that I changed PS1 to no longer include the \t escape sequence (added in a previous section), so the time was no longer a part of the prompt. Then I used date +%H%M to display the time in a format I like better. But it appears on a different line than the prompt. Tidying this up using echo -n ... as shown below works with Bash 2.0+, but appears not to work with Bash 1.14.7: apparently the prompt is drawn in a different way, and the following method results in overlapping text.

2156
[giles@nikola:~] PROMPT_COMMAND="echo -n [$(date +%H%M)]"
[2156][giles@nikola:~]$
[2156][giles@nikola:~]$ d
bin   mail
[2157][giles@nikola:~]$ unset PROMPT_COMMAND
[giles@nikola:~]

echo -n ... controls the output of the date command and suppresses the trailing newline, allowing the prompt to appear all on one line. At the end, I used the unset command to remove the PROMPT_COMMAND environment variable.

11.10. Controlling the Size and Appearance of $PWD

Unix allows long file names, which can lead to the value of $PWD being very long. Some people (notably the default RedHat prompt) choose to use the basename of the current working directory (ie. "giles" if $PWD="/home/giles"). I like more info than that, but it's often desirable to limit the length of the directory name, and it makes the most sense to truncate on the left.

#   How many characters of the $PWD should be kept
local pwdmaxlen=30
#   Indicator that there has been directory truncation:
#trunc_symbol="<"
local trunc_symbol="..."
if [ ${#PWD} -gt $pwdmaxlen ]
then
	local pwdoffset=$(( ${#PWD} - $pwdmaxlen ))
	newPWD="${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}"
else
	newPWD=${PWD}
fi

Bash Prompts

Simple Red-hat style prompt:

function redhat {
PS1="[\u@\h \W]\\$ "
PS2="> "
}

Colored prompt

#!/bin/bash
function proml {
local BLUE="\[\033[0;34m\]"
local RED="\[\033[0;31m\]"
local LIGHT_RED="\[\033[1;31m\]"
local WHITE="\[\033[1;37m\]"
local LIGHT_GRAY="\[\033[0;37m\]"
case $TERM in
xterm*)
TITLEBAR='\[\033]0;\u@\h:\w\007\]'
;;
*)
TITLEBAR=""
;;
esac

PS1="${TITLEBAR}\
$BLUE[$RED\$(date +%H%M)$BLUE]\
$BLUE[$LIGHT_RED\u@\h:\w$BLUE]\
$WHITE\$$LIGHT_GRAY "
PS2='> '
PS4='+ '
}


Prompt with ~ replacement. It looks like does not make any sense anymore (\w incorporate home directory folding), but some ideas might be reused:

#!/bin/bash
# termwide prompt with tty number
# by Giles - created 2 November 98
#
# $Revision: 1.2 $ $Author: giles $
# $Source: /home/giles/.bashprompt/bashthemes/RCS/twtty,v $
# $Log: twtty,v $
# Revision 1.2 1999/03/25 01:37:51 giles
#
# Revision 1.1 1999/03/25 01:35:26 giles
# Initial revision
#
# This is a variant on "termwide" that incorporates the tty number.
#
# 24 March 99 - use of sed with \{$cut\} where $cut is an integer
# means that this probably now requires a GNU version of sed.

function prompt_command {

TERMWIDTH=${COLUMNS}

# Calculate the width of the prompt:

hostnam=$(echo -n $HOSTNAME | sed -e "s/[\.].*//")
# "whoami" and "pwd" include a trailing newline
usernam=$(whoami)
cur_tty=$(tty | sed -e "s/.*tty\(.*\)/\1/")
newPWD="${PWD}"
# Add all the accessories below ...
let promptsize=$(echo -n "--(${usernam}@${hostnam}:${cur_tty})---(${PWD})--" \
| wc -c | tr -d " ")
let fillsize=${TERMWIDTH}-${promptsize}
fill=""
while [ "$fillsize" -gt "0" ]
do
fill="${fill}-"
let fillsize=${fillsize}-1
done

if [ "$fillsize" -lt "0" ]
then
let cut=3-${fillsize}
newPWD="...$(echo -n $PWD | sed -e "s/\(^.\{$cut\}\)\(.*\)/\2/")"
fi
}

PROMPT_COMMAND=prompt_command

function twtty {

local GRAY="\[\033[1;30m\]"
local LIGHT_GRAY="\[\033[0;37m\]"
local WHITE="\[\033[1;37m\]"
local NO_COLOUR="\[\033[0m\]"

local LIGHT_BLUE="\[\033[1;34m\]"
local YELLOW="\[\033[1;33m\]"

case $TERM in
xterm*)
TITLEBAR='\[\033]0;\u@\h:\w\007\]'
;;
*)
TITLEBAR=""
;;
esac

PS1="$TITLEBAR\
$YELLOW-$LIGHT_BLUE-(\
$YELLOW\$usernam$LIGHT_BLUE@$YELLOW\$hostnam$LIGHT_BLUE:$WHITE\$cur_tty\
${LIGHT_BLUE})-${YELLOW}-\${fill}${LIGHT_BLUE}-(\
$YELLOW\${newPWD}\
$LIGHT_BLUE)-$YELLOW-\
\n\
$YELLOW-$LIGHT_BLUE-(\
$YELLOW\$(date +%H%M)$LIGHT_BLUE:$YELLOW\$(date \"+%a,%d %b %y\")\
$LIGHT_BLUE:$WHITE\$$LIGHT_BLUE)-\
$YELLOW-\
$NO_COLOUR "

PS2="$LIGHT_BLUE-$YELLOW-$YELLOW-$NO_COLOUR "

}

Root prompt

#!/bin/bash

# $Author: giles $, $Date: 1999/07/29 17:59:59 $
# $Source: /home/giles/.bashprompt/bashthemes/RCS/rprom,v $
# $Revision: 1.3 $
#
# $Log: rprom,v $
# Revision 1.3 1999/07/29 17:59:59 giles
# Terminated colours correctly at prompt end.
#
# Revision 1.2 1999/06/06 18:13:30 giles
# Made the length of the kept part of the PWD flexible - a variable
# named near the beginning of the script.
#
# Revision 1.1 1999/06/06 18:02:35 giles
# Initial revision
#

function prompt_command {
# How many characters of the $PWD should be kept
local pwd_length=30
# Create TotalMeg variable: sum of visible file sizes in current directory
local TotalBytes=0
for Bytes in $(ls -l | grep "^-" | cut -c30-41)
do
let TotalBytes=$TotalBytes+$Bytes
done
TotalMeg=$(echo -e "scale=3 \nx=$TotalBytes/1048576\n if (x<1) {print \"0\"} \n
print x \nquit" | bc)

# Count visible files:
let files=$(ls -l | grep "^-" | wc -l | tr -d " ")
let hiddenfiles=$(ls -l -d .* | grep "^-" | wc -l | tr -d " ")
let executables=$(ls -l | grep ^-..x | wc -l | tr -d " ")
let directories=$(ls -l | grep "^d" | wc -l | tr -d " ")
let hiddendirectories=$(ls -l -d .* | grep "^d" | wc -l | tr -d " ")-2

if [ $(echo -n $PWD | wc -c | tr -d " ") -gt $pwd_length ]
then
newPWD="...$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
else
newPWD="$(echo -n $PWD)"
fi
}

PROMPT_COMMAND=prompt_command

function rprom {

local BLUE="\[\033[0;34m\]"
local LIGHT_GRAY="\[\033[0;37m\]"
local LIGHT_GREEN="\[\033[1;32m\]"
local LIGHT_BLUE="\[\033[1;34m\]"
local LIGHT_CYAN="\[\033[1;36m\]"
local YELLOW="\[\033[1;33m\]"
local WHITE="\[\033[1;37m\]"
local RED="\[\033[0;31m\]"
local NO_COLOUR="\[\033[0m\]"

case $TERM in
xterm*)
TITLEBAR='\[\033]0;\u@\h:\w\007\]'
;;
*)
TITLEBAR=""
;;
esac

PS1="$TITLEBAR\
$BLUE[$RED\$(date +%H%M)$BLUE]\
$BLUE[$RED\u@\h$BLUE]\
$BLUE[\
$LIGHT_GRAY\${files}.\${hiddenfiles}-\
$LIGHT_GREEN\${executables}x \
$LIGHT_GRAY(\${TotalMeg}Mb) \
$LIGHT_BLUE\${directories}.\
\${hiddendirectories}d\
$BLUE]\
\n\
$BLUE[$RED\$newPWD$BLUE]\
$WHITE\$\
\
$NO_COLOUR "
PS2='> '
PS4='+ '
}

Bash-prompts This article is Copyright 1998-2003 by Douglas Barton. For non-commercial use only.

---------------------- Begin Copyrighted Material -------------------
$Revision: 1.11 $
$Date: 2003/01/19 06:17:23 $


	

This article is Copyright 1998-2003 by Douglas Barton. All non-commercial uses of this article are granted explicitly; providing that my name, this copyright notice, and all material between and including the lines that say "Begin Copyrighted Material" and "End of Copyrighted Material" are reproduced intact. All commercial uses of this article are explicitly reserved, and must be arranged with the author.

I hope that does not sound extreme, but writing documentation is one of the things I do for a living, and after putting as many hours into something as I have this article, I feel that protecting my interests is well within reason. :) Please feel free to send any comments, suggestions, corrections or questions to [email protected].

I made reference to the "termcap" file that comes with the FreeBSD distribution, the xterm source code, and the "ctlseqs.ms," both from XFree86 3.3.2.3. Of course I also used the Bash man pages.

The information in this article is specific to Bash version 2.x. Although the general information about xterm and ANSI escape sequences is probably applicable to other shells, I have not tested it, and have no intention of doing so. Those using Bash 1.14.x can accomplish most of the things mentioned here by using the octal equivalents of the various escape sequences (e.g., substituting \033 for \e, \007 for \a, etc.) and deleting the \[ and \] characters that indicate the boundaries of the non-printable portions of the prompt to Bash 2. This was tested briefly, but I give no guarantees that what you want to do with Bash 1.14 will work.

If you need help with the basics of creating a prompt string, please see the PROMPTING section of the Bash man page.

By including escape sequences in your prompt you can affect various aspects of the terminal you are using; be that an xterm, console device, or other terminal emulation. For example, xterm has the following built in escape sequences (from misc.c in the xterm source):


        0: /* new icon name and title*/
        1: /* new icon name only */
        2: /* new title only */

The icon name escape sequences work for X window managers like AfterStep and Window Maker. The title bar sequences work in most window managers. Both also work for some Windows based terminal emulators. An example is PuTTY, which can be found at http://www.chiark.greenend.org.uk/~sgtatham/putty/

Here is a simple example of a prompt using those attributes.

PS1='\[\e]1;My Desk\a\e]2;${PWD}\a\]\
[\u@ME \w]\n \#\$ '
To make things easier to read, I used a \ at the end of the first line (which is interpreted by the shell as literally escaping the Return at the end of that line) to continue the string onto the next line. You can use all the examples in this article as they are here, or you can join the lines. Make sure to delete the \ if you join them. Here is how to interpret the elements of that line.
PS1=	set the shell variable PS1 equal to the string between the two
	' marks. Since this variable is only used by Bash, there is no
	need to export it.
\[	start a sequence of non-printing characters
\e	an ASCII escape character (033 octal)
]1;	xterm escape sequence for the name of the icon
My Desk	literal text string
\a	an ASCII bell character (007 octal)
This ends the first xterm sequence.
\e]2;${PWD}\a
Put the present working directory in the xterm titlebar. I like to use ${PWD} here because \w puts ~ in the title when you use just 'cd' to return to your home.
\]	ends the non-printing character sequence

[\u@ME \w]\n
[	literal [ character
\u	the username of the current user
@ME	literal characters
\w	the current working directory
]	literal ] character
\n	newline

\#\$
\#	the command number of this command
\$	if the effective UID is 0, a #, otherwise a $
Here are some examples of what the prompt looks like using the above string.

While I am in my home directory:

[myusername@ME ~]
 22$

Another directory:
[myusername@ME /usr/ports/shells/bash2]
 23$
Now assume you would like to add color to your prompt. The following will make your prompt a lovely shade of blue, with the caveat that not all ANSI sequences display exactly the same on all terminals.
PS1='\[\e]1;My Desk\a\e]2;${PWD}\a\
\e[0;34m\]\
[\u@ME \w]\n \#\$ \
\[\e[m\]'
The astute reader will notice that there are two changes to the previous string. Before the first \] which indicates the end of the non-printing sequence, the ANSI escape code for the color blue was added.
\e[	ANSI escape sequence indicator
0;	use the default attribute (i.e., no bold, underline, etc.)
34	use blue for the foreground color
m	end of ANSI escape indicator
At the end of the prompt we have included another set of non-printable characters with the ANSI escape sequence for "cancel all attributes." This will prevent the text you type in at the prompt from being colored, or otherwise affected.

Two very popular uses of color are to indicate that the user has become root, and to use different colors for prompts on different hosts. Because I log into machines on a lot of different hosts, I have developed the following prompt system which allows me to simply change the two variables below for each host.

PROMPT_HOSTNAME='ME'
PROMPT_COLOR='0;34m'

# If I am root, set the prompt to bright red
if [ ${UID} -eq 0 ]; then
PROMPT_COLOR='1;31m'
fi

PS1='\[\e]1;${PROMPT_HOSTNAME}\a\e]2;${PROMPT_HOSTNAME}:${PWD}\a\
\e[${PROMPT_COLOR}\]\
[\u@${PROMPT_HOSTNAME} \w]\n \#\$ \
\[\e[m\]'
There are other ANSI attributes that can be added, such as bold, inverse (or reverse) video, blink and underline. Not all attributes are supported on all terminals however. For example, the blink attribute is not available in xterm. Underline is generally not available in cons25. A little experimentation with your terminal type will show you what you need to do to achieve the effect you want.

A chart with the most common escape sequences of interest; and which ones are supported on xterm, cons25 and vt100 terminals is appended to the end of this article. If your system uses terminfo instead of termcap, your escape codes may be different.

Let us say that you would like the hostname part of the prompt to be in reverse video so that it stands out more than the rest.

PS1='\[\e[0;34m\]\
[\u@\e[7mME\e[27m \w]\n \#\$ \
\[\e[m\]'
The \e[7m sequence is the code for reverse video. On an xterm you can use the sequence \e[27m to cancel the reverse attribute. On other terminals you would either have to use \e[m to cancel all attributes (which works fine if you are not using color) or use the same color sequence you used previously to restore only the color attribute.

If you have the same .bash_profile/.bashrc on a machine that you log into from different terminal types, you may find the following to be of use. This allows you to customize your prompt according to what attributes are supported based on the various types of terminals you use. This is based on my experience, you will probably need to modify it to serve your needs.

PROMPT_HOSTNAME='ME'
PROMPT_COLOR='0;34m'

# If I am root, set the prompt to bright red
if [ ${UID} -eq 0 ]; then
PROMPT_COLOR='1;31m'
fi

case ${TERM} in
        xterm*)
PS1='\[\e]1;${PROMPT_HOSTNAME}\a\e]2;${PROMPT_HOSTNAME}:${PWD}\a\
\e[${PROMPT_COLOR}\][\u@${PROMPT_HOSTNAME} \w]\n \#\$ \[\e[m\]'
        ;;
        vt100)
PS1='[\u@${PROMPT_HOSTNAME} \w]\n \#\$ '
        ;;
        *)
PS1='\[\e[${PROMPT_COLOR}\][\u@${PROMPT_HOSTNAME} \w]\n \#\$ \[\e[m\]'
        ;;
esac

Below is a chart of various interesting attributes for prompting purposes. The first column is a description of the attribute. The second column is the termcap code for that attribute. For more information check 'man 5 termcap'. If the escape code listed does not work for your terminal, check the termcap file for your machine. Those using the terminfo system should check that file and the documentation for it to find the information they need.

The last three columns contain the codes for the various terminals, if they are supported. Below this chart is a very long and rather obnoxious prompt string that gives examples of these attributes, and should allow you to test your terminal to see what it can support. It also has the various color codes so you can use it as a reference as well. The bold attribute when combined with a color has the effect of "brightening" the color displayed. On some terminals this makes it an entirely different color.

When creating an escape sequence, you can combine the various elements. For example, if you want a string that is bold, underlined, with a red foreground and a green background you would use:

\e[1;4;31;42m
To read this chart, keep in mind that an ANSI escape sequence starts with \e[ and ends with a literal m. Thus from the chart, the code to turn on the bold attribute is \e[1m. The \e[m sequence turns off all ANSI attributes, and is the only way to cancel things like bold and underline on most terminals. Obviously, "NO" means that terminal does not support that attribute. The ^G for bell is the traditional "hold down the Control key and press G" combination. It can of course be represented in a Bash 2 prompt string with \a. On most terminals, "inverse" and "standout" are identical. Most terminals display unsupported attributes as bold.
Attribute     termcap	xterm	cons25	vt100
---------------------------------------------
bold on		md	1	1	1
bold off		22	[m

inverse on	mr	7	7	7
inverse off		27	[m

standout on	so	7	7	7
standout off	se	27	[m	[m

underline on	us	4	NO	4
underline off	ue	24		[m

blink on	mb	NO	5	5
blink off		25	[m	[m

blank/invis	mk	8

bell		bl	^G	^G	^G

all attr off	me	[m	[m	[m

Here is a sample prompt with the list of color codes included. Where more than one color is indicated it means that color is known to display differently on different terminal types. Other colors may be similarly affected.
PS1='[\u@TEST \w]\n \#\$ \n\
\[\
\e[1mBold Text\e[m\n\
\e[4mUnderline Text\e[m\n\
\e[5mBlink Text\e[m\n\
\e[7mInverse Text\e[m\]\n\
Should be normal text
Foreground colors:
\[\
\e[0;30m30: Black\n\
\e[0;31m31: Red\n\
\e[0;32m32: Green\n\
\e[0;33m33: Yellow\Orange\n\
\e[0;34m34: Blue\n\
\e[0;35m35: Magenta\n\
\e[0;36m36: Cyan\n\
\e[0;37m37: Light Gray\Black\n\
\e[0;39m39: Default\n\
Bright foreground colors:
\e[1;30m30: Dark Gray\n\
\e[1;31m31: Red\n\
\e[1;32m32: Green\n\
\e[1;33m33: Yellow\n\
\e[1;34m34: Blue\n\
\e[1;35m35: Magenta\n\
\e[1;36m36: Cyan\n\
\e[1;37m37: White\n\
\e[0;39m39: Default\n\
\e[m\]Background colors:
\[\e[1;37m\e[40m40: Black\e[0;49m\n\
\e[41m41: Red\e[0;49m\n\
\e[42m42: Green\e[0;49m\n\
\e[43m43: Yellow\Orange\e[0;49m\n\
\e[44m44: Blue\e[0;49m\n\
\e[45m45: Magenta\e[0;49m\n\
\e[46m46: Cyan\e[0;49m\n\
\e[47m47: Light Gray\Black\e[0;49m\n\
\e[49m49: Default\e[m\]\n'

While I know that nothing in this article is going to cure cancer, I hope that it does bring some small joy to your life, and that you have as much fun using this information as I did bringing it all together.

-------------------- End of Copyrighted Material -----------------------

An excellent web page with resources for other shells can be found at: http://sunsite.unc.edu/LDP/HOWTO/mini/Xterm-Title.html

The Linux Bash prompt HOWTO maintained by Giles Orr can be found at: http://www.dreaming.org/~giles/bashprompt/ There are a lot of interesting ideas in that extensive document, but he makes use of a lot of external programs in his prompts (even when he doesn't have to), which is something I think is a little excessive. But each to his own. :)

[Sept 9, 2003] Updated link to Bash prompt howto:

http://en.tldp.org/HOWTO/Bash-Prompt-HOWTO/index.html

CEE UCL HelpDesk How do I change my system prompt


Recommended Links

Google matched content

Softpanorama Recommended

Please visit  Heiner Steven SHELLdorado  the best shell scripting site on the Internet

Google Directory - Computers Software Operating Systems Unix Shell bash

Sys Admin v15, i12 Korn Shell Nuances (only the last part of the article is relevant to the topic).

Enhancing Shell Prompts by Daniel Robbins ([email protected]) President-CEO, Gentoo Technologies, Inc. September 2000

Why stick with the standard boring shell prompt when you can easily make it colorful and more informative? In this tip, Daniel Robbins will show you how to get your shell prompt just the way you like it, as well as how to dynamically update your X terminal's title bar.

Highlighting Linux Command Prompts with the PROMPT_COMMAND Variable by Kirk Becker Sys Admin Magazine vol. 12, No. 1  January, 2003

How to make custom prompts

ONLamp.com Understanding Shell Prompts

Bash-prompts  Copyright 1998-2003 by Douglas Barton.

$Revision: 1.11 $
$Date: 2003/01/19 06:17:23 $

All non-commercial uses of this article are granted explicitly; providing
that my name, this copyright notice, and all material between and
including the lines that say "Begin Copyrighted Material" and "End of
Copyrighted Material" are reproduced intact. All commercial uses of
this article are explicitly reserved, and must be arranged with the
author.

Prompt Depending on Connection Type -- interesting idea from the point view of security

170_myprompt --readymade, pretty complex color prompt.

LinuxLookup.com Articles Shell Prompt Customization -- some simpler prompt variants (bash)

Bash Prompt HOWTO Example Prompts -- prompt perversions. Well, if you like stuff like this, you should definitely have a look at BASHISH, the shell prompt theme (no RPMs, though).

bashprompt-0.4.5b6.tar.gz

[Nov 24, 2004] Bash Prompt HOWTO. Bash Prompt HOWTO  -- this is an overkill ;-), but still there is a useful information, for example: 11.10. Controlling the Size and Appearance of $PWD

Unix allows long file names, which can lead to the value of $PWD being very long. Some people (notably the default RedHat prompt) choose to use the basename of the current working directory (ie. "giles" if $PWD="/home/giles"). I like more info than that, but it's often desirable to limit the length of the directory name, and it makes the most sense to truncate on the left.

#   How many characters of the $PWD should be kept
local pwdmaxlen=30
#   Indicator that there has been directory truncation:
#trunc_symbol="<"
local trunc_symbol="..."
if [ ${#PWD} -gt $pwdmaxlen ]
then
	local pwdoffset=$(( ${#PWD} - $pwdmaxlen ))
	newPWD="${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}"
else
	newPWD=${PWD}
fi

The above code can be executed as part of PROMPT_COMMAND, and the environment variable generated (newPWD) can then be included in the prompt. Thanks to Alexander Mikhailian who rewrote the code to utilize new Bash functionality, thus speeding it up considerably.

Risto Juola (risto AT risto.net) wrote to say that he preferred to have the "~" in the $newPWD, so he wrote another version:

pwd_length=20

DIR=`pwd`

echo $DIR | grep "^$HOME" >> /dev/null

if [ $? -eq 0 ]
then
  CURRDIR=`echo $DIR | awk -F$HOME '{print $2}'`
  newPWD="~$CURRDIR"

  if [ $(echo -n $newPWD | wc -c | tr -d " ") -gt $pwd_length ]
  then
    newPWD="~/..$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
  fi
elif [ "$DIR" = "$HOME" ]
then
  newPWD="~"
elif [ $(echo -n $PWD | wc -c | tr -d " ") -gt $pwd_length ]
then
  newPWD="..$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
else
  newPWD="$(echo -n $PWD)"
fi

Relative speed: the first version takes about 0.45 seconds on an unloaded 486SX25. Risto's version takes about 0.80 to 0.95 seconds. The variation in this case is due to whether or not truncation is required.

Bash-prompts

The FreeBSD Diary -- Changing your bash prompt. See also Bash-prompts

Then I added the following to the bottom of .bash_profile:

# set prompt: ``username@hostname:/directory $ ''
PS1="[\u@\h:\w] " 
case `id -u` in
      0) PS1="${PS1}# ";;
      *) PS1="${PS1}$ ";;
esac

This will give you a prompt something like this:

[fleur@flossy:/usr/home/fleur]#

Better Prompts - $PS1

Linux Orbit - Server or desktop, GNU-Linux just works -- Useful description of PS1 and PS2 in bash (non-applicable to korn shell)

The PS1 variable is your primary prompt. Depending upon how your system is configured, the PS1 variable will vary. PS1 is normally defined in /etc/profile, but can be overridden by defining it again in ~/.bash_profile [TRANSLATION: Because /etc/profile is only writable by root, you can only override the environmental variables there by redefining them in your ~/.bash_profile]. bash recognizes special characters prefixed with a backslash for the PS1 variable. These characters are:

t -- the current time in HH:MM:SS format
d -- the date in "Weekday Month Date" format (eg, "Tue May 26")
newline
s -- the name of the shell
w -- the current working directory
W -- the basename of the current working directory
u  -- the username of the current user
h -- the hostname
# the command number of this command
! -- the history number of this command
$ -- if the effective UID is 0, a #, otherwise a $

These are the characters that allow you to change your prompt. If your PS1 variable is set as PS1="[u@h W]$", then your prompt will look like this:

[xconsole@localhost /etc]$

If you were to change it to the following: PS1="[\t\s]$ ", you would get:

[12:18:24 bash]$

In addition to these special backslash characters, you can use commands. For instance, to have your prompt run as a fortune, you can do this:

PS1="`fortune` $ "

Notice that you have to use "`" instead of "'". This changes PS1 to the following:

He is no lawyer who cannot take two sides. $

As you can see, bash is very lenient about the way you configure it, so knock yourself out. The PS2 variable is your secondary prompt and is used when you have typed an incomplete command, or when you have typed a backslash at the end of a command [TRANSLATION: A backslash at the end of a command in bash tells it that you are not done with the command. This is when it will present you with the PS2 variable. bash is also smart enough to know when the command you are typing is incomplete, and in such a case, it will present you with the PS2 variable]. When you are presented with the PS2 variable, bash expects you to finish the command before it will attempt to run it. To see your current PS2 variable, run the following command:

xconsole$ if [ -f /etc/profile ]; then

When you press ENTER, you will see that you have a new prompt:

xconsole$ if [ -f /etc/profile ]; then >

This prompt is the PS2 variable. You can also view it with echo $PS2. In the above example with the if statement, we did not add a backslash character right at the end of the command, but bash knew the command was incomplete. As with PS1, it is defined in /etc/profile, and can be overridden and redefined in ~/.bash_profile. It recognizes the special backslashed characters, as well as other programs like fortune [TRANSLATION: Whatever applies to PS1, applies to PS2 as well].

Linux Tips

Setting the PS1 Environment Variable In Redhat Linux Distributions

There have been instances where administrators have had difficulty setting the PS1 environment variable on their system when using Redhat Linux distributions. The PS1 environment variable controls the prompt on the command line, and can be used by users to tell what system they are on, the directory they are currently in, the current date and more depending on how this variable is configured. This tip will explain the strange method used by Redhat distributions to control the PS1 variable, and the options administrators have to work around it.

Understanding the Problem

When Bash begins to run when the user logs in, the following sequence of events will normally occur unless Bash is invoked with the -noprofile option. These events are specific for a common Redhat distribution upon initial install. Please see the How Linux Works CTDP Guide for complete information on files that are run when bash starts, or read the bash(1) man page.

  1. Bash runs /etc/profile if it exists
  2. Bash runs $HOME/.bash_profile
    1. The $HOME/.bash_profile script runs the $HOME/.bashrc script
      1. The $HOME/.bashrc script runs /etc/bashrc

Note: The $HOME name used above indicates the user home directory. If you examine the sequence of events above, it is obvious that the last step is rather unusual. Normally scripts are run for system wide control, then scripts that are individually set up for specific users are run last. In the above sequence of events a script set for system control is run after running two scripts that are in the user's home directory. This has the effect of stepping on any values any individual user may set the PS1 environment variable to. When a user makes a modification to this variable in the .bash_profile script in their home directory, the change will be ineffective. This is because the /etc/bashrc file contains the following:

# /etc/bashrc

# System wide functions and aliases
# Environment stuff goes in /etc/profile

# For some unknown reason bash refuses to inherit
# PS1 in some circumstances that I can't figure out.
# Putting PS1 here ensures that it gets loaded every time.
PS1="[\u@\h \W]\\$ "

This will set the PS1 variable to the value shown here. The PS1 value is normally initially set in the /etc/profile script for system wide default use, then the individual users may modify or change this value in the $HOME/.bash_profile script for their own use. If you note the comment above, the writer of the /etc/bashrc file states that "bash refuses to inherit PS1 in some circumstances".

Solving the Problem

Normally, the correct thing to do would be to run the /etc/bashrc script from the /etc/profile script. The /etc/bashrc script should not change the PS1 variable, but is normally used to set up aliases, Therefore in addition to doing the below changes the administrator may want to comment out the line in /etc/bashrc that sets the PS1 variable, and add the three lines from the $HOME/.bashrc file that run the /etc/bashrc script to the end of the /etc/profile script. The /etc/bashrc script can then be used by the administrator for setting global alias values.

I think setting the PS1 variable in the $HOME/.bash_profile or $HOME/.bashrc script should be sufficient to avoid the above problem so long as you be sure to set it. Since the $HOME/.bashrc file contains the following:

# .bashrc

# User specific aliases and functions

# Source global definitions
if [ -f /etc/bashrc ]; then
	. /etc/bashrc
fi

The easiest thing to do is comment out the three lines that make up the if statement (put the # character at the start of each line), which would run the /etc/bashrc script and add the following line or one like it to the file to set the PS1 value.

PS1="[\u@\h \w]\\$ "

This line can be added to the $HOME/.bash_profile script file instead but would involve changing two files. Adding it to the $HOME/.bash_profile script is the more appropriate thing to do from a system standpoint since the $HOME/.bashrc file is for aliases. The administrator would want to make these changes to all these files in their user's home directories, or have their users do it.

Making the change for all future users

The directory /etc/skel contains files that are used by the system to create files for new users in their home directories. To make this change effective for users that are added to the system in the future, the /etc/skel/.bashrc file should be changed and the /etc/skel/.bash_profile file should be changed if it was used to set the PS1 variable.

The meaning of the characters in the prompt string settings

The following list shows the meanings of the special characters used to define the PS1 and PS2 prompt strings.

If you want the full path of the current directory, use a small w in the string shown above. Read the bash(1) man page for more information. Also read The Bash Reference Manual in the directory /usr/doc/bash2-doc-2.03/bash.ps. It can be accessed from an X session by double clicking on it while using the file manager. Bash builtins are described in the file in the directory /usr/doc/bash2-doc-2.03/builtins.ps.

Comments or Problems

If anyone finds that they have some difficulties in making this change that may be related to this tip, please send an email to the administrator of this website describing the distribution of Linux being used, the version of bash and any other circumstances that pertain to the problem. Also include copies of $HOME/.bash_profile, and $HOME/.bashrc. We cannot guarantee a response, but will do what we can to look into the problem and update the tip as it is appropriate.

Date of Original Tip:
July 12, 2000
Author:
Mark Allen

BASH command return value

My PS1 prompt has the following string,

PS1='($?)\u@\h:\w =>'

In this case, when my command fails the BASH variable $? value is displayed
in my prompt. What is happening is that a command return value stays there
until an new command is issued. A newline for the shell will still return the
previous $? value. $? value is never reset until a new command is issued.

(0)subb3@myhost:~ =>
(0)subb3@myhost:~ => lssdfh  <== This is no command
(258)subb3@myhost:~ =>
(258)subb3@myhost:~ =>
(258)subb3@myhost:~ =>
(258)subb3@myhost:~ => ls
     <file listing>
(0)subb3@myhost:~ =>

When I change the PS1 sring to,

PS1='($?)`whoami`@\h:\w =>'

The return value for $? is immediately displayed in the next prompt.

(0)subb3@myhost:~ =>
(0)subb3@myhost:~ => lssdfh
(258)subb3@myhost:~ =>
(0)subb3@myhost:~ =>
(0)subb3@myhost:~ => ls
     <file listing>
(0)subb3@myhost:~ => ls o
ls: o: No such file or directory
(1)subb3@myhost:~ =>

In BASH, why does the "\u" and "whoami" make a big difference for the $? value in
PS1 string? The BASH version is 2.04.

--

Subba Rao
[email protected]
http://pws.prserv.net/truemax/

 => Time is relative. Here is a new way to look at time. <=
http://www.smcinnovations.com

 

> $? value is never reset until a new command is issued.

Of course, since it's the exit status of the last command.

> PS1='($?)`whoami`@\h:\w =>'
>
> The return value for $? is immediately displayed in the next prompt.

It's the exit status of the command substitution, the last command
executed.

--
``The lyf so short, the craft so long to lerne.'' - Chaucer
( ``Discere est Dolere'' -- chet)

Chet Ramey, CWRU    [email protected]    http://cnswww.cns.cwru.edu/~chet/
 


Reference

Bash escape sequences

When  executing  interactively,  bash displays the primary prompt PS1 when it is ready to read  a  command,  and  the secondary  prompt PS2 when it needs more input to complete a command.  Bash allows these prompt strings  to  be  customized by inserting a number of backslash-escaped special characters that are decoded as follows:
              \a     an ASCII bell character (07)
              \d     the date  in  "Weekday  Month  Date"  format
                     (e.g., "Tue May 26")
              \e     an ASCII escape character (033)
              \h     the hostname up to the first `.'
              \H     the hostname
              \j     the  number of jobs currently managed by the  shell
              \l     the basename of the shell's terminal  device  name
              \n     newline
              \r     carriage return
              \s     the  name  of  the shell, the basename of $0  (the portion following the final slash)
              \t     the current time in 24-hour HH:MM:SS format
              \T     the current time in 12-hour HH:MM:SS format
              \@     the current time in 12-hour am/pm format
              \u     the username of the current user
              \v     the version of bash (e.g., 2.00)
              \V     the release of bash,  version  +  patchlevel  (e.g., 2.00.0)
              \w     the current working directory
              \W   the  basename  of the current working directory
              \!     the history number of this command
              \#     the command number of this command
              \$     if the effective UID is 0, a #, otherwise  a  $
              \nnn   the  character  corresponding  to  the octal
                     number nnn
              \\     a backslash
              \[     begin a sequence of non-printing characters,
                     which could be used to embed a terminal con�
                     trol sequence into the prompt
              \]     end a sequence of non-printing characters

developerWorks Linux Tip Prompt magic -- nice table of special characters in PS1-PS4.

Sequence Description
\a The ASCII bell character (you can also type \007)
\d Date in "Wed Sep 06" format
\e ASCII escape character (you can also type \033)
\h First part of hostname (such as "mybox")
\H Full hostname (such as "mybox.mydomain.com")
\j The number of processes you've suspended in this shell by hitting ^Z
\l The name of the shell's terminal device (such as "ttyp4")
\n Newline
\r Carriage return
\s The name of the shell executable (such as "bash")
\t Time in 24-hour format (such as "23:01:01")
\T Time in 12-hour format (such as "11:01:01")
\@ Time in 12-hour format with am/pm
\u Your username
\v Version of bash (such as 2.04)
\V Bash version, including patchlevel
\w Current working directory (such as "/home/drobbins")
\W The "basename" of the current working directory (such as "drobbins")
\! Current command's position in the history buffer
\# Command number (this will count up at each prompt, as long as you type something)
\$ If you are not root, inserts a "$"; if you are root, you get a "#"
\xxx Inserts an ASCII character based on three-digit number xxx (replace unused digits with zeros, such as "\007")
\\ A backslash
\[ This sequence should appear before a sequence of characters that don't move the cursor (like color escape sequences). This allows bash to calculate word wrapping correctly.
\] This sequence should appear after a sequence of non-printing characters.

So, there you have all of bash's special backslashed escape sequences. Play around with them for a bit to get a feel for how they work. After you've done a little testing, it's time to add some color.

Colorizing

Bash Prompt HOWTO  -- this is an overkill ;-)

Bash Prompts

Simple Red-hat style prompt:

function redhat {
PS1="[\u@\h \W]\\$ "
PS2="> "
}

Colored prompt

#!/bin/bash
function proml {
local       BLUE="\[\033[0;34m\]"
local        RED="\[\033[0;31m\]"
local  LIGHT_RED="\[\033[1;31m\]"
local      WHITE="\[\033[1;37m\]"
local LIGHT_GRAY="\[\033[0;37m\]"
case $TERM in
    xterm*)
        TITLEBAR='\[\033]0;\u@\h:\w\007\]'
        ;;
    *)
        TITLEBAR=""
        ;;
esac

PS1="${TITLEBAR}\
$BLUE[$RED\$(date +%H%M)$BLUE]\
$BLUE[$LIGHT_RED\u@\h:\w$BLUE]\
$WHITE\$$LIGHT_GRAY "
PS2='> '
PS4='+ '
}

Root prompt

#!/bin/bash

# $Author: giles $, $Date: 1999/07/29 17:59:59 $
# $Source: /home/giles/.bashprompt/bashthemes/RCS/rprom,v $
# $Revision: 1.3 $
#
# $Log: rprom,v $
# Revision 1.3  1999/07/29 17:59:59  giles
# Terminated colours correctly at prompt end.
#
# Revision 1.2  1999/06/06 18:13:30  giles
# Made the length of the kept part of the PWD flexible - a variable
# named near the beginning of the script.
#
# Revision 1.1  1999/06/06 18:02:35  giles
# Initial revision
#

function prompt_command {
#   How many characters of the $PWD should be kept
local pwd_length=30
#   Create TotalMeg variable: sum of visible file sizes in current directory
local TotalBytes=0
for Bytes in $(ls -l | grep "^-" | cut -c30-41)
do
    let TotalBytes=$TotalBytes+$Bytes
done
TotalMeg=$(echo -e "scale=3 \nx=$TotalBytes/1048576\n if (x<1) {print \"0\"} \n
print x \nquit" | bc)

#   Count visible files:
let files=$(ls -l | grep "^-" | wc -l | tr -d " ")
let hiddenfiles=$(ls -l -d .* | grep "^-" | wc -l | tr -d " ")
let executables=$(ls -l | grep ^-..x | wc -l | tr -d " ")
let directories=$(ls -l | grep "^d" | wc -l | tr -d " ")
let hiddendirectories=$(ls -l -d .* | grep "^d" | wc -l | tr -d " ")-2

if [ $(echo -n $PWD | wc -c | tr -d " ") -gt $pwd_length ]
then
   newPWD="...$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
else
   newPWD="$(echo -n $PWD)"
fi
}

PROMPT_COMMAND=prompt_command

function rprom {

local    BLUE="\[\033[0;34m\]"
local    LIGHT_GRAY="\[\033[0;37m\]"
local    LIGHT_GREEN="\[\033[1;32m\]"
local    LIGHT_BLUE="\[\033[1;34m\]"
local    LIGHT_CYAN="\[\033[1;36m\]"
local    YELLOW="\[\033[1;33m\]"
local    WHITE="\[\033[1;37m\]"
local    RED="\[\033[0;31m\]"
local    NO_COLOUR="\[\033[0m\]"

case $TERM in 

   xterm*)
        TITLEBAR='\[\033]0;\u@\h:\w\007\]'
        ;;
    *)
        TITLEBAR=""
        ;;
esac

PS1="$TITLEBAR\
$BLUE[$RED\$(date +%H%M)$BLUE]\
$BLUE[$RED\u@\h$BLUE]\
$BLUE[\
$LIGHT_GRAY\${files}.\${hiddenfiles}-\
$LIGHT_GREEN\${executables}x \
$LIGHT_GRAY(\${TotalMeg}Mb) \
$LIGHT_BLUE\${directories}.\
\${hiddendirectories}d\
$BLUE]\
\n\
$BLUE[$RED\$newPWD$BLUE]\
$WHITE\$\
\
$NO_COLOUR "
PS2='> '
PS4='+ '
}

Etc

 

Last modified: June 04, 2016

directive is used to test whether Readline is in `emacs' or `vi' mode. This may be used in conjunction with the `set keymap' command, for instance, to set bindings in the `emacs-standard' and `emacs-ctlx' keymaps only if Readline is starting out in `emacs' mode. `term' The `term=' form may be used to include terminal-specific key bindings, perhaps to bind the key sequences output by the terminal's function keys. The word on the right side of the `=' is tested against the full name of the terminal and the portion of the terminal name before the first `-'. This allows SUN to match both SUN and SUN-CMD, for instance. `application' The APPLICATION construct is used to include application-specific settings. Each program using the Readline library sets the APPLICATION NAME, and you can test for it. This could be used to bind key sequences to
functions useful for a specific program.
`$endif' This command terminates an `$if' command. `$else' Commands in this branch of the `$if' directive are executed if the test fails.

The following command adds a key sequence that quotes the current or previous word in Bash:
$if bash
# Quote the current or previous word
"\C-xq": "\eb\"\ef\""
$endif
 

My .inputrc file is here

Last update by Hermann Heimhardt on October 7, 2001

BASH inputrc Function Binding to Key Ignored


From: William Bloom
Subject: BASH inputrc Function Binding to Key Ignored
Date: Thu, 7 Jun 2001 21:56:02 -0700 (MST)

I have built BASH 2.05.0(1)-release from source for Solaris
8 as well as FreeBSD 4.3 and have observed a difference from
BASH 2.04 in the handling of the TAB keybinding when 'vi'
editing mode is in use with a POSIX mode BASH session.
I've not seen comments about this in the archive, and the
new behavior continues even after I've applied all patches
from the BASH homepage.  I also don't see comments in the
changelog that seem relevant (perhaps I've missed it).

As an example, suppose  I have a very simple inputrc file as
follows...

        TAB: complete
        C-b: complete-into-braces

...as part of a profile that contains a 'set -o vi'.  The
login shell is /usr/local/bin/sh (a link to BASH) in order
to have a POSIX session.  The above inputrc is simply
intended to let TAB have the same completion behavior to
which some of my users are accustomed from non-POSIX BASH
use.

I find that in this case, the 'C-b' binding is honored but
the TAB binding is ignored.  -After- the session is started,
the TAB binding may be enabled using 'bind -f .inputrc', at
which time the TAB binding is not ignored.

Stranger yet, if the account is changed to use
/usr/local/bin/bash as the login shell, then the session
login now honors the TAB binding.  If the session switches
to POSIX mode (set -o posix) after login, however, then the
TAB binding automagically disappears (although the C-b binding
remains).

Is this behavior related to POSIX compliance, which (I
believe) does not call for TAB to be bound?  Are those users
who want POSIX mode and vi-style command line editing, but
yet aren't ready to give up their accustomed TAB-complete
binding, going to have to have an explicit...

        bind 'TAB: complete'

...to their login profile as of 2.0.5?


Bill

Lee D. Rothstein - Re remapping Cygwin 'bash' readline functions to PC keys

John, thanks for the <C-V> heads up! Others had
suggested, variations of 'cat < foo' and 'od -c'. (The
former I got to work, the latter remains a mystery.)
Your solution, besides being the most straight-forward,
is also a great tool to have around. Apparently, it's a
feature of Cygwin, or 'bash', since it doesn't work in
a naked 'cmd.exe' window. I'll be sure to add it to my
documentation.
 
Unfortunately the key combos I'm trying to map to
are: <^-->> and <^-<-> (control- and the right and left
arrow keys). It turns out that the character string
outputs for both the:
 
* naked key
* shift - and the naked key
* control- and the naked key


are all the same.

 

Actually, I no longer consider these to be KIDs; these
are the character string graphemic outputs of hitting
the key. I'll continue to reserve "KIDs" for when one
represents these [and the key isomorphisms]
with '/e...', 'C-...', etc. "notation".
 
Apparently (?), the only way to discriminate among these
three alternatives is with Scan Codes. Apparently, all
the -x-ish stuff I've used (Microemacs, Thompson shell
command line editing) that can discriminate among the
three alternatives all use Scan Codes (?).
 
 - Any way to map to Scan Codes to 'bash' 'readline'
   functions under Cygwin?
   + Or to key "names" like: '<CTRL-left-arrow>',
     '<CTRL-HOME>'
 - Any interest among Cygwin developers in adding
   this?
 
>At 2003-02-19 08:02 AM -0800, John Mapole wrote:
...
>You can build your own KID table. Once at the cygwin
>prompt you can type <C-V>, that's control-V, followed
>by the key.  On my machine, if I type <C-V><INSERT>, I
>see "^[[2~".  This is the same as "\e[2~".
>
>Why these mapping are like this relates to how windows
>maps them and then how cygwin maps them.  Something I
>am now very clear on.
>
>Hope this helps some.
>
>John Mapoles
>
>--- "Lee D. Rothstein" <lee at veritech dot com> wrote:
...
>> Q1 -- When you remap a 'bash' Edit Mode function in
>> .inputrc, it looks like this:
>>
>> "\e[3~":      delete-char # DEL key
>>
>> The entity in double quotes ("\e[3~"), I'm calling
>> the "key ID (KID)". In the above '.inputrc' declaration,
>> the function 'delete-char' being remapped from its
>> default key assignment to the KID -- "\e[3~" -- the
>> <DEL> key.
>>
>> What are the KIDs of the following IBM PC keys
>> (specified below with facsimiles of the key caps
>> contained in angle brackets -- '<...>')?
>>
>> Cursor control key pad
>> ----------------------
>> <HOME>
>> <END>
>> <left-arrow>
>> <right-arrow>
>> <PAGE_UP>
>> <PAGE_DOWN>
>> <INSERT>
>>
>> Numeric pad
>> -----------
>> <->
>> <+>
>> <ENTER>
>> </>


 

I should have included in the above lists, all variations
of the above with the control, alt and shift keys.


 

>> In general, I'd like a table that maps the KIDs for all
>> 104 keys on the keyboard I use. Or, better still, is
>> there a way to use scan codes?
>>
>> (Incidentally, what makes finding a table of these
>> KIDs so difficult is the failure of the documentation
>> to assign this concept a unique, or even a consistent
>> word.)
>>
>> Q2
>> --
>>
>> Is there a way to make the <INSERT> key a toggle
>> between the insert and overwrite modes of 'bash'
>> edit mode?
>>
>> I used to have these figured out for 'Microemacs',
>> but that was half a lifetime ago, for me, & Microemacs
>> supported scan codes, if I remember correctly.


--
Lee D. Rothstein -- lee at veritech dot com
VeriTech -- 603-424-2900
7 Merry Meeting Drive
Merrimack, NH 03054-2934


 

--
Unsubscribe info:      http://cygwin.com/ml/#unsubscribe-simple
Bug reporting:         http://cygwin.com/bugs.html
Documentation:         http://cygwin.com/docs.html
FAQ:                   http://cygwin.com/faq/

Why can't solaris be more like linux...

Matthew Frederico [email protected]
16 May 2003 12:53:12 -0600

I agree with Nick on this one. I don't know about the inputrc stuff but
I do know that in the past, I would set my TERM to VT220 then all my
keys worked correctly.  Try:
% export TERM=VT220


On Fri, 2003-05-16 at 12:23, Nicholas Leippe wrote:
> On Friday 16 May 2003 10:14 am, you wrote:
> > I've been given access to a bunch of solaris 8 boxen here at work
> > lately, and i'm finding it difficult to move around in it because of
> > shell differences... i guess i've always taken the default setups of any
> > linux distro i've ever tried for granted.  On the solaris box, I've had
> > my shell set to BASH as that is my preference... but i still get "^?"
> > characters while trying to backspace in vi and from ftp... and i get "~"
> > when trying to "delete".  Anyone know of a quick way to get the shell
> > setup "correctly"?
> 
> Trying creating a ~/.inputrc file (see READLINE section in the bash man page).
> My global inputrc in linux (/etc/inputrc) is:
> 
> set meta-flag on
> set input-meta on
> set convert-meta off
> set output-meta on
> "\e0d": backward-word
> "\e0c": forward-word
> "\e[h": beginning-of-line
> "\e[f": end-of-line
> "\e[1~": beginning-of-line
> "\e[4~": end-of-line
> "\e[5~": beginning-of-history
> "\e[6~": end-of-history
> "\e[3~": delete-char
> "\e[2~": quoted-insert
> "\e[g": beginning-of-line
> "\e[e": beginning-of-line
> "\e[H": beginning-of-line
> "\e[F": end-of-line
> "\e[G": beginning-of-line
> "\e[E": beginning-of-line
> "\e[s": beginning-of-line
> DEL: backward-delete-char
> 
> 
> Some of that came from Redhat 6.2's /etc/inputrc.  You could also try copying 
> it from whatever distro you have installed nearby.  Also, check your TERM 
> variable.  When that's not correct, some things can get really wierd. (eg it 
> shouldn't be 'xterm' when in the console)
> 
> 
> Nick

-- 
Matthew Frederico
Unwired Networks
[email protected]
http://www.unwirednetworks.com

Re [ale] Automating vi-style history editing in bash


On Wed, Mar 01, 2000 at 04:55:31PM -0500, David S. Jackson wrote:
> On Wed, Mar 01, 2000 at 03:09:22PM -0500 Fulton Green <[email protected]> wrote:
> > I know how to set up bash to let me edit previous commands vi-style by typing
> > set -o vi
> > or
> > export EDITOR=vi
>
> These two things are not really the same at all. Your shell's
> editing mode (if it is bash) is set with set -o vi or set -o
> emacs. Or you can emulate yet another editor by setting the
> $readline variable in .inputrc.
>
> However, the $EDITOR variable is something else. Applications
> check if this variable exists if no editor is defined by default
> for that application. You can set emacs editing mode for the
> shell and set the $EDITOR variable to vi. No problem.
 

True for bash, and you can do this in ksh as well. However, ksh also examines
$EDITOR if the readline mode hasn't been set with 'set -o vi|emacs'. At least
this is the behavior on Solaris 2.6, whose Korn shell doesn't appear to do
the inputrc thing. My apologies for confusing Korn's behavior with bash's.
 

> > at the command line. My problem: under Red Hat 6.1, I can't seem to get
> > either of these to have an effect when I put either of them in .bash_profile
> > or .bashrc
>
> Again, the statements don't mean the same thing. But just open
> an Xterm (or whatever) and type set -o vi at the command prompt.
 

And that works for me.
 

> > In fact, doing the "set" command in .bashrc ensures that I won't
> > even be able to *manually* set the mode from the command line.
>
> This shouldn't be true. Using the set command shouldn't prohibit
> you from 'unsetting' the editing mode. I normally use emacs mode
 

It *is* true in my circumstance, but it's iff the 'set -o vi' is executed in
my .bashrc file. And at this point, I should mention that I didn't notice any
problem until I upgraded Red Hat to 6.0. I also confirmed the problem on a
fresh RH 6.1 box. I'm going to change the main runlevel in /etc/inittab from
5 to 3 (i.e., don't start out in an X server) to see if that affects anything.
 

> Are you using an .inputrc?
 

I'm not. That could very well be the problem if the global inputrc has
trash, as pointed out by earlier emails. I don't have the computer in question
in front of me at the moment, but I could almost swear that RH 6.0 or 6.1 did
away with /etc/inputrc . Or was that /etc/skel/.inputrc ?
 

Thanks for the help,

Fulton Green
http://www.FultonGreen.com/

Random Findings

Re Suggestions for corrections to executable.el - use of PATHEXT

From: Lennart Borgman
Subject: Re: Suggestions for corrections to executable.el - use of PATHEXT
Date: Sun, 12 Sep 2004 12:56:08 +0200

From: "Eli Zaretskii" <[email protected]>

> First, I'm not sure we should look at PATHEXT.  That variable is AFAIK
> looked at by the shell, so if we want Emacs behave _exactly_ like the
> shell does, we should at least look at the value of SHELL and/or
> ComSpec (and COMSPEC for older systems).  I mean, what if the user's
> shell is Bash, which AFAIK doesn't look at PATHEXT at all?  And if the
> shell is COMMAND.COM, then ".cmd" should not be in the list.  Etc.,
> etc.

PATHEXT is looked at by cmd.exe (the default shell on the NT hereditary
line). I do not know if it is used by command.com (the default shell on the
95 line) but I doubt it. When I tested now I found that the Run entry in
Windows Start menu honor the default extensions for PATHEXT (.com, .exe.,
.bat, .cmd). It does not however not recognize .pl which I have in my
PATHEXT (cmd.exe recognize it). I am using NT4 when testing this.

So perhaps not even ms windows is consistent here. What seems clear however
is that the main purpose of PATHEXT is as far as I can see to make it easier
for the user when entering a command interactively. The user may for example
type "notepad" instead of "notepad.exe".

PATHEXT is set by the user and expresses the users wish to type less. It
seems reasonable to use PATHEXT for this purpose in Emacs too. The variable
executable-binary-suffixes is (if I understand this correctly) used for this
purpose by executable-find. This is however not clearly expressed in the
documentation.

A note: w32-shell-execute does something quite different. It calls the ms
windows API ShellExecute to do the action associated with a certain "verb"
on a file type (on windows this means file extension). Typical verbs are
"open" and "print". Windows Explorer uses this.

Having said all this I just want to say that I regret that I took this issue
up without looking closer at the problem.

- Lennart



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater�s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright � 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: June 04, 2016