Howto Decorate Bash Prompt

1032

The Bash shell provide users with a very customisable prompt through the variable named PS1 for the primary prompt and PS2 for the secondary prompt. This Howto is the basics to get started.

Simplest method to test changes to the prompt is by entering the following at the prompt and the immediate changes will be shown at the user prompt in the next press of the “Enter” key.

export PS1='Hello world$ '

This will display the words “Hello world$” followed by a space before the cursor.

Backslash-escaped Special Character

Users find it useful with their server hostname, user name, date, time, directory and all sorts of stuff displayed with their prompt. The list can be found at Bash Prompt from TLDP, here are listed a few;

  1. d – the date  in  “Weekday  Month  Date”  format (e.g., “Tue May 26”)
  2. e – indicate an ASCII escape character (033)
  3. h – the hostname up to the first ‘.’
  4. n – newline
  5. t – the current time in 24-hour HH:MM:SS format
  6. T – the current time in 12-hour HH:MM:SS format
  7. u – the username of the current user
  8. W – the basename of the current working directory

Example 1: Common user name, server host name and working directory display

export PS1='[u@h W]$’

Example 2: Display current time and prompt in 2nd line

export PS1=’d [u@h W]nt $’

Colours

Font colour is a assigned with the sequence [e[colourcode] where the colour code in combination of font style and ansi colour code (see TLDP). All colour escape sequences must be followed by letter ‘m’.

Ansi colour code

  1. Black      0;30m
  2. Dark Gray     1;30m
  3. Blue        0;34m    
  4. Light Blue    1;34m
  5. Green       0;32m    
  6. Light Green   1;32m
  7. Cyan        0;36m    
  8. Light Cyan    1;36m
  9. Red         0;31m    
  10. Light Red     1;31m
  11. Purple      0;35m    
  12. Light Purple  1;35m
  13. Brown       0;33m    
  14. Yellow        1;33m
  15. Light Gray  0;37m    
  16. White         1;37m

[e[m] Closing colour code

Example 1: Display common prompt as green and following character typed is also green. Its shown 2 ways of writing same prompt

export PS1='[[e[0;32m]u@h W]$ ‘export PS1='[[33[0;32m]u@h W]$ ‘

Example 2: Display common prompt as green and following character typed is default colour

export PS1='[[e[0;32m]u@h W[e[m[[$ ‘

Example 3: Contrast colours to highlight

export PS1='[e[1;34m]u[e[1;33m]@[e[1;32m]h[e[1;37m]([e[1;31m]W[e[1;37m]) [e[1;36m]$ [e[0m]’

Saving changes

Changes can be saved to ~/.bashrc to make sure that it is applied each time a user access the terminal.

To make this global, add the PS1 line to the /etc/bashrc. This however is always overridden by the user’s ~/.bashrc configuration.

Example of ~/.bashrc:

# .bashrc# Source global definitions
if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi
# User specific aliases and functions