I have defined the color red using tput

red=$(tput setaf 1)

to colorize warnings in my program. This works fine:

printf '%sfail\n' "$red"
# prints 'fail' in red

But on one occasion I would like to print out the escape sequence as-is, something like:


How would I do this? I know printf has a %q flag but it escape others stuff I don't want to.

  • Is it just the ESC (0x1b) character you want to convert to \E, or other control characters? Jul 2, 2015 at 11:22

3 Answers 3


Sounds like you want the opposite of printing them literally, you want those escape characters converted to a printable descriptive form like \E or \033, ^[...

If it's just the ESC (0x1b) character you want to convert to \E, then with ksh93, zsh or bash (typically, the same ones that also support that non-standard %q), you can do:

printf '%s\n' "${red//$'\e'/\\E}"

Or pipe to sed $'s/\e/\\\\E/g'

For a more generic approach at converting non-graphical characters, you can use:

$ printf %s "$red" | od -A n -vt c # POSIX
 033   [   3   1   m
$ printf %s "$red" | sed -n l # POSIX
$ printf '%s\n' "${(qqqq)red}" # zsh
$ printf '%s\n' "$red" | cat -vt # some cat implementations
$ printf %s "$red" | uconv -x ':: [:Cc:]; ::Hex;' # ICU tools
$ printf %s "$red" | uconv -x ':: [:Cc:]; ::Name;' # ICU tools

Use od, hexdump, xxd, or similar to print binary data in human-readable form. For example:

$ tput setaf 1 | od -c
0000000 033   [   3   1   m

You can use printf directly, eg

printf "\033[31mfail"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .