Shell – How to print a variable that contains unprintable characters

character encodingshellspecial charactersvariable

I want to display the value of the $IFS variable, which could contain unprintable characters (for example: newline).

I used the following command to do so:

echo -n "$IFS" | hexdump -C

Which worked great in my case.

But is there anything wrong in using this command? For example, does echo replaces some unprintable characters with some other characters before printing them to its stdout, or some other problem like that?

Best Answer

Especially with IFS, you absolutely want to quote it, since otherwise it, well turns to nothing. You did that already, so no problem there.

As for echo, it depends on the shell. Some versions of echo handle backslash-escapes by default, some don't. Bash's doesn't, zsh's does:

$ bash -c 'echo "foo\nbar"'
foo\nbar
$ zsh -c 'echo "foo\nbar"'
foo
bar

It's better to use printf instead: printf "%s" "$IFS" | hexdump -C.

See also: Why is printf better than echo?

printf "%q" "$IFS" also works in Bash and zsh.

That should keep you fine, except that Bash can't handle NUL bytes (\0) at all, zsh can. Bash:

$ var=$'foo\0bar'
$ printf "%q\n" "$var"
foo

zsh:

$ var=$'foo\0bar'
$ printf "%q\n" "$var"
foo$'\0'bar
Related Question