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:
echodoes not expand backslash escapes unless you give-e(or thexpg_echoshell option is set).-Eturns expansion off. bash'secho -eknows\eand\033for the escape character. - dash, the default system shell (
/bin/sh) on Debian systems, takes only-n. It always expands backslash escapes and prints-eas an ordinary word. Soecho -e "\033[1m"prints-efollowed by the escape sequence. - POSIX itself says it is not possible to use
echoportably unless the text has no backslash escapes and the first argument does not start with-followed bye,Eorn.
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).\eis not in the POSIX list, although bash and some versions of dash accept it. printfdoes not add a newline; put\nat 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.
Related
- Escape sequences
- Escape sequence table
- Bash prompt wraps onto the same line: mark color codes in PS1
- Shell and tmux basics
- Script fails with "/bin/bash^M: bad interpreter" or "$'\r': command not found": Windows line endings
Sources
- POSIX echo: APPLICATION USAGE (echo is not portable; use printf)
- POSIX printf: escape sequences and \ddd octal bytes
- Bash Reference Manual: echo, -e, -E and xpg_echo
- [dash(1), Debian manual page: echo [-n]](https://manpages.debian.org/bookworm/dash/dash.1.en.html)
- Debian package dash: the default system shell on Debian