Bash Prompt HOWTO:
Prev | Chapter 6. ANSI Escape Sequences: Colours and Cursor Movement | Next

# 6.2. Cursor Movement

ANSI escape sequences allow you to move the cursor around the screen at will. This is more useful for full screen user interfaces generated by shell scripts, but can also be used in prompts. The movement escape sequences are as follows:

    - Position the Cursor:
      \033[<L>;<C>H
         Or
      \033[<L>;<C>f
      puts the cursor at line L and column C.
    - Move the cursor up N lines:
      \033[<N>A
    - Move the cursor down N lines:
      \033[<N>B
    - Move the cursor forward N columns:
      \033[<N>C
    - Move the cursor backward N columns:
      \033[<N>D

    - Clear the screen, move to (0,0):
      \033[2J
    - Erase to end of line:
      \033[K

    - Save cursor position:
      \033[s
    - Restore cursor position:
      \033[u

The latter two codes are NOT honoured by many terminal emulators. The only ones that I'm aware of that do are xterm and nxterm - even though the majority of terminal emulators are based on xterm code. As far as I can tell, rxvt, kvt, xiterm, and Eterm do not support them. They are supported on the console.

Try putting in the following line of code at the prompt (it's a little clearer what it does if the prompt is several lines down the terminal when you put this in): `echo -en "\033[7A\033[1;35m BASH \033[7B\033[6D"` This should move the cursor seven lines up screen, print the word "`BASH` ", and then return to where it started to produce a normal prompt. This isn't a prompt: it's just a demonstration of moving the cursor on screen, using colour to emphasize what has been done.

Save this in a file called "clock":

    #!/bin/bash

    function prompt_command {
    let prompt_x=$COLUMNS-5
    }

    PROMPT_COMMAND=prompt_command

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

    PS1="${TITLEBAR}\
    \[\033[s\033[1;\$(echo -n \${prompt_x})H\]\
    $BLUE[$LIGHT_RED\$(date +%H%M)$BLUE]\[\033[u\033[1A\]
    $BLUE[$LIGHT_RED\u@\h:\w$BLUE]\
    $WHITE\$$NO_COLOUR "
    PS2='> '
    PS4='+ '
    }

This prompt is fairly plain, except that it keeps a 24 hour clock in the upper right corner of the terminal (even if the terminal is resized). This will NOT work on the terminal emulators that I mentioned that don't accept the save and restore cursor position codes. If you try to run this prompt in any of those terminal emulators, the clock will appear correctly, but the prompt will be trapped on the second line of the terminal.

See also Section 12.9 for a more extensive use of these codes.

Prev | Home | Next
Colours | Up | Xterm Title Bar Manipulations