Changing bash prompt

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search

← Using aliasesHomeSetting shell options →

This article is a stub. You can help us by expanding it.

  • Task: You need to customize your bash prompt by editing PS1 variable.
  • Display, your current prompt setting, enter:
echo $PS1

Sample outputs:

  • For testing purpose set PS1 as follows and notice the change:
PS1='your wish is my command : '

Sample outputs:

vivek@vivek-desktop:~$ PS1='your wish is my command : '
your wish is my command : 

Customizing Prompt

Bash shell allows prompt strings to be customized by inserting a number of backslash-escaped special characters. Quoting from the bash man page:

Sequence Description
\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 (FQDN)
\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
\A The current time in 24-hour HH:MM format
\u The username of the current user
\v The version of bash (e.g., 2.00)
\V T The release of bash, version + patch level (e.g., 2.00.0)
\w The current working directory, with $HOME abbreviated with a tilde
\W The basename of the current working directory, with $HOME abbreviated with a tilde
\! 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 control sequence into the prompt
\] End a sequence of non-printing characters

You can use above backslash-escaped sequence to display name of the host with current working directory:

PS1='\h \W $ '

Adding color to prompt

It is quite easy to add colors to your prompt. Set green color promot for normal user account[1]:

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

And red color prompt for root user account:

export PS1='\[\e[1;31m\][\u@\h \W]\$\[\e[0m\] '

How do I make prompt setting permanent?

Edit your ~/.bashrc or ~/.bash_profile

vi ~/.bashrc

Append your PS1 definition:

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

Save and close the file.


If PROMPT_COMMAND environment variable set, the value is executed as a command prior to issuing each primary prompt. In other words, the contents of this variable are executed as a regular Bash command just before Bash displays a prompt[2]


External links

← Using aliasesHomeSetting shell options →