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
\E
, or other control characters?