Thursday, December 13, 2012

printf instead of echo-e

It is a common need to echo content to files in scripts. But it could turn out a bit tricky to handle escape sequences like new line.

echo is provided as part of binutils but shell can provide its own too. Default handling of escape sequence varies from shell to shell. In case of Ubuntu default shell is dash(debian shell). It handles escape sequences by default. Thus sh -c "echo -e 'foo\nbar'" could end up as "-e foo\nbar" instead of foo followed bar in new line.

But printf is more portable and reliable than echo-e. Something with print is

sh -c 'printf "%b\n%b\n" "for" "bar"'

This yields consistent and more reliable results across mostly used shell variants.