Bash command to print string in unambiguous form

bashstring

I am wondering whether there exists a command in bash to print a string in a way exposes the special character it contains.

For example, suppose that a=$'\a\0\b\e'; does there exists a function to print \a\0\b\e literally from $a?

The closest I have got so far is by using the l command from sed:

echo "$a"  | sed -n 'l'

which returns \a\000\b\033$, but the notation is different from that inside $'', and it doesn't work if the string contains newlines.

Best Answer

var=$'a b \10 c'
printf %q "$var"
    $'a b \b c'

This works in bash. I do not know how compatible this is.

Related Question