9

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:

\E[31mfail

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? – Stéphane Chazelas Jul 2 '15 at 11:22
10

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
\033[31m$
$ printf '%s\n' "${(qqqq)red}" # zsh
$'\033[31m'
$ printf '%s\n' "$red" | cat -vt # some cat implementations
^[[31m
$ printf %s "$red" | uconv -x ':: [:Cc:]; ::Hex;' # ICU tools
\u001B[31m
$ printf %s "$red" | uconv -x ':: [:Cc:]; ::Name;' # ICU tools
\N{<control-001B>}[31m
5

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
0000005
1

You can use printf directly, eg

printf "\033[31mfail"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.