Cursor control characters in a bash script

This post was written by eli on October 23, 2015
Posted Under: Linux,Software

To control the cursor’s position with a plain bash “echo” command, use the fact that the $’something‘ pseudo-variable interprets that something more or less like a C escape sequence. So the ESC character, having ASCII code 0x1b, can be generated with $’0x1b’. $’\e’ is also OK, by the way.

There are plenty of sources for TTY commands, for example this and this.

So, to jump to the upper-left corner of the screen, just go

$ echo -n $'\x1b'[H

Alternatively, one can use echo’s -e flag, which is the method chosen in /etc/init.d/functions to produce color-changing escape characters. So the “home” sequence could likewise be

$ echo -en \\033[H

As easy as that.

Add a Comment

required, use real name
required, will not be published
optional, your blog address