How to Escape Characters in Bash

Fumbani Banda Feb 02, 2024
  1. Escape Characters
  2. Using double quotes
  3. More Escape Characters in Bash
How to Escape Characters in Bash

This tutorial explains what escape characters are and provides an informative list of escape characters.

Escape Characters

Escape characters are characters that represent an alternative interpretation other than themselves. There is no definitive list with all the characters that need to be escaped in bash. However, a recommended general rule says if in doubt, escape it.

Using double quotes

Using double quotes around escape characters preserves their literal meaning.

Let us use the asterisk, *, with the echo command to demonstrate this. On the terminal, typing, echo * displays all the files in the current directory. However, enclosing * in double-quotes displays the asterisk only on the standard output.

echo "*"

It displays the following output.

*

More Escape Characters in Bash

There is no definitive list with all the characters that need to be escaped in bash. You can find out by testing some of these characters. The following bash script provides insight into which characters need to be escaped and the representation of the escaped characters.

for x in {0..127} ;do
    printf -v char \\%o $x
    printf -v char $char
    printf -v res "%q" "$char"
    esc=Escape
    [ "$char" = "$res" ] && esc=-
    printf "%02X %s %-7s\n" $x $esc "$res"
done | sort

The script displays the output below. I have only displayed the first 11 characters. The first field has the hex value of byte, and the second file has Escape if a character needs to be escaped or - if not. The last part shows the representation of the character when escaping it.

00 Escape ''
01 Escape $'\001'
02 Escape $'\002'
03 Escape $'\003'
04 Escape $'\004'
05 Escape $'\005'
06 Escape $'\006'
07 Escape $'\a'
08 Escape $'\b'
09 Escape $'\t'
0A Escape $'\n'
0B Escape $'\v'
0C Escape $'\f'
0D Escape $'\r'
0E Escape $'\016'
0F Escape $'\017'
10 Escape $'\020'
Fumbani Banda avatar Fumbani Banda avatar

Fumbani is a tech enthusiast. He enjoys writing on Linux and Python as well as contributing to open-source projects.

LinkedIn GitHub