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 or zsh 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

or

echo ${.sh.version}
# Version JM 93u 2011-02-08

or

echo $KSH_VERSION
# Version JM 93u 2011-02-08

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
Basic Prompt

Add the colors

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
Color table

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 $ '

My prompt
My prompt

  • Dinesh Devaraj

    great article very nice ...

    But this does not work in regular ksh or restricted ksh. The user has to invoke ksh93 first and only then these commands will work