Strovent SystemsSign in
Reference

Print escape sequences with echo -e or printf: why it differs between shells

echo -e works in bash but prints "-e" in dash, the default /bin/sh on Debian. Why echo is not portable, and how to print colors and escape codes with printf.

You want a script to print a color or another terminal escape sequence. echo -e "\033[1mbold\033[0m" works in your shell, but in a script it prints a literal -e, or prints \033[1m as text. The echo command behaves differently in different shells, and POSIX says so.

Why echo differs

  • bash: echo does not expand backslash escapes unless you give -e (or the xpg_echo shell option is set). -E turns expansion off. bash's echo -e knows \e and \033 for the escape character.
  • dash, the default system shell (/bin/sh) on Debian systems, takes only -n. It always expands backslash escapes and prints -e as an ordinary word. So echo -e "\033[1m" prints -e followed by the escape sequence.
  • POSIX itself says it is not possible to use echo portably unless the text has no backslash escapes and the first argument does not start with - followed by e, E or n.

A script that starts with #!/bin/sh therefore gets dash's echo where /bin/sh is dash, and bash's echo on systems where /bin/sh is bash.

Use printf

printf is specified by POSIX and behaves the same in every shell. Its first argument is a format string in which \n, \t and \ddd (an octal byte) are expanded:

printf '\033[1mbold\033[0m normal\n'
printf '\033[31m%s\033[0m\n' "$message"
  • Use \033 (octal 33 = ESC). \e is not in the POSIX list, although bash and some versions of dash accept it.
  • printf does not add a newline; put \n at the end.
  • Put variable text in an argument with %s, not in the format string, so a % or backslash in the text is printed as it is.

Check what you sent

To see the exact bytes, pipe the output through od -c:

printf '\033[1mx\n' | od -c

The escape character shows as 033. If you see \ 0 3 3 instead, the escape was not expanded.

For what the sequences do, see Escape sequences and Escape sequence table. If a stray sequence leaves the terminal in a strange state, see Fix a terminal full of garbage after printing a binary file.

Sources

Spotted a mistake? Email [email protected].