Terminal Codes

In this lesson you will learn about how the terminal can be manipulated to display non-standard characters that direct it to change its appearance.

Although not directly related to bash, if you spend any time at a terminal, then it will pay off to understand how the terminal works with non-standard characters. You’ve already learned about the readline library and terminal options and how certain keystrokes can be ‘caught’ and handled in other ways before they get to the terminal. Here we look at how other non-standard characters can be handled in the bash shell.

Non-standard characters are characters like tab, newline, carriage return, and even the end of file characters. They don’t form part of words, or necessarily print anything to the screen, but they are bytes interpreted by the shell and the terminal if they get that far.

Note: The focus here is on ANSI-standard escape codes. Rarely, you might come across more complex escapes for specific terminal contexts, but this is beyond the scope of a ‘practical’ guide.

How Important is this Lesson?

This lesson is somewhat more advanced, and probably not essential to using bash at the start. It can also be hard to grasp, so if you’re new to bash I recommend returning to it later if it’s hard to understand the first time you read it.

However, knowledge of this area will catapult you to an elite of bash users that understand how terminals can be manipulated, and also enable you to understand how your prompt can be manipulated.

Non-Printable Characters

The terminal you use has what are described as printable characters and non-printable characters.

For example, typing a character like a (normally) results in the terminal adding an a to the screen. But there are other characters that tell the terminal to do different things that don’t necessarily involve writing a character you’d recognise.

It’s easy to forget this, but not everything that is sent to the computer is directly printed to the screen. The terminal driver takes what it is given (which is one or more bytes) and decides what to do with it. It might decide to print it (if it’s a ‘normal’ character), or it might tell the computer to emit a beep, or it might change the colour of the terminal, or delete and go back a space, or it might send a message to the running program to tell it to exit.

When looking at non-printable characters, it’s useful to be aware of a couple of utilities that help you understand what’s going on. The first of these is a familiar one: echo.

Using echo

You’re already familiar with echo, but it has some sometimes-useful flags you’ve not already used in this book:

Get hands-on with 1200+ tech skills courses.