The printf command

The printf command works like echo, except the first argument you provide to it is a format string:

$ printf '%s\n' 'Hello!'
Hello!

Notice that we had to put the format string in single quotes, to prevent the backslash from having special meaning to the shell. Notice also that we didn't have to use double quotes to get the newline from \n; the printf command did that for us.

You can use printf in much the same way you would use a printf() function in other languages, such as C. It supports most of the same format specifications as the printf(1) system command; you can type man 1 printf to see a list.

It's easier to print tricky strings with printf, where echo might struggle:

$ printf '%s\n' -n -n $ string=-n $ printf '%s\n' ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.