bash – Why Doesn’t printf Escape Newlines?

bashnewlinesprintf

$ printf "hi"
hi$ printf "hi\n"
hi
$ printf "hi\\n"
hi

Why doesn't the last line print hi\n?

Best Answer

This is nothing to do with printf, and everything to do with the argument that you have given to printf.

In a double-quoted string, the shell turns \\ into \. So the argument that you have given to printf is actually hi\n, which of course printf then performs its own escape sequence processing on.

In a double-quoted string, the escaping done through \ by the shell is specifically limited to affecting the ␊, \, `, $, and " characters. You will find that \n gets passed to printf as-is. So the argument that you have given to printf is actually hi\n again.

Be careful about putting escape sequences into the format string for printf. Only some have defined meanings in the Single Unix Specification. \n is defined, but \c is actually not, for example.

Further reading

Related Question