Saturday, 4 May 2013

Setting a Custom Prompt in Ksh

Customizing the prompt, a.k.a. $PS1, is usually the first thing I do when I'm trying a new shell; if you are using bash  there are many resources on the internet that teaches you how to do it.

But what if you are using a less-known shell like the Korn Shell? Usually the informations are outdated or incomplete. This tutorial is intended for the original ksh93, if you don't know which version you are running run.
ksh --version
# version         sh (AT&T Research) 93u 2011-02-08
echo ${.sh.version}
# Version JM 93u 2013-03-07
# Version JM 93u 2013-03-07

Basic prompt

Let's start with a very simple example, I set the prompt to the classic user@host $
export PS1='$(logname)@$(hostname -s) $ '
$(logname) returns the output of the command enclosed in parentheses.
To show the current path use the $PWD variable.
export PS1='$(logname)@$(hostname -s):$PWD $ '
The result is
umadm@unixmantra:/home/umadmin $
A black-and-white (in my case, grey-and-sand) prompt is so '80s!

Let's add some colors.

A string between $'…' is like a normal string, but \E is escaped to \033.

 Color escape sequences have to be enclosed in \E[…m, for example $'\E[32mhello will display the string 'hello' in green.

To have a red prompt set $PS1 to
export PS1=$'\E[31m$(logname)@$(hostname -s):$PWD $ \E[0m'
Note the \E[0m before the closing ', this resets the text color.

You can add more attributes to \E[…m, the complete form is:
\E[bgcolor;textattribute;fgcolor m

The possible values for bgcolor are integers between 40 and 47, for fgcolor are integers between 30 and 37 and for tetxattribute are 0, 1, 4, 5, 7 and 8.

Refer to the following table for the colors

Color table Explanation:

The values for textattribute have the following meaning:

0: normal text
1: bold text or light color, depending on the term preferences
4: underscore text
5: blinking text(yep!)
7: inverse
8: concealed text

Putting all together

My prompt is the following, you can modify it to fulfill your needs.
export PS1=$'\E[35;7m$(logname)@$(hostname -s)\E[0m:\E[32;1m$PWD \E[0m $ 


  1. how to set this permanent ? "export PS1='$(logname)@$(hostname -s) $ ' "

    1. add entry in your home profile "~/.profile" , make sure you have +x permission on the file.

  2. Thank you..this was really helpful!!

  3. This is a great article.

    I searched around to understand why we have \E[…m pattern

    " Color escape sequences have to be enclosed in \E[…m, for example $'\E[32mhello will display the string 'hello' in green."