Thursday, June 25, 2009

Printing Strings in Shell Scripts

echo's nice. printf is nicer.

I still see people use echo. Heck, I still use echo.

But POSIX shells have had printf as a built-in for twenty years. The syntax is like C's printf().

You don't always need fancy formatting, so echo's still good for simple strings, like this:

echo 'What are you -- nuts?'
but there's no reason to use echo -n when you can use printf. None.

Just the reverse. Experiments like this:

time for i in {1..10000}; do printf $i; done > /dev/null
time for i in {1..10000}; do echo -n $i; done > /dev/null
will show you that printf is about 10% faster.

Similarly, you can discard echo -e "foo\tbar" for printf "foo\tbar\n" . Why keep a bunch of flags to echo in your head if you're comfy with printf from other languages?

No comments: