$ printf "hi" hi$ printf "hi\n" hi $ printf "hi\\n" hi
Why doesn't the last line print
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
This is nothing to do with
printf, and everything to do with the argument that you have given to
In a double-quoted string, the shell turns
\. 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 ␊,
" characters. You will find that
\n gets passed to
printf as-is. So the argument that you have given to
printf is actually
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.
Within double quotes,
\\n is an escaped (quoted) backslash followed by a
n. This is given to
printf will output a newline.
Within double quotes (still),
\n is the string
printf receives a
\n string and will print a newline.
Within double quotes, backslash is special only when preceding another backslash, a newline, or any of
". "Special" means that it removes the special meaning of the next character. If a backslash precedes any other character (
n for example), then it's just a backslash character.
This is explained in the POSIX standard.
\n in a
printf format string, use
printf '\\n' or
printf "\\\\n", or use
printf '%s' '\n'
In general, the
printf format string should be single quoted and any variable data should be given as additional arguments to be inserted into the format string:
printf 'This is how you write a newline: %s\n' '\n'
Ok, lets add another point of view.
There are two levels of interpretation here at play. One is the shell, the other is the command (in this case
printf) interpretation of the arguments received.
Inside double quotes The shell will leave alone most of the sequences backslash-character, this is the common result:
$ printf '%s\n' "\a \b \c \d ... \z \$ \` \\ " \a \b \c \d ... \z $ ` \
\ which, being especial to the shell, get their
So, testing both the strings you used (and others), we get:
$ printf '%s\n' "hi\n" "hi\\n" "hi\\\n" "hi\\\\n" "hi\\\\\n" hi\n hi\n hi\\n hi\\n hi\\\n
The shell converts pairs of
\\ to one
\. And leaves alone
printf has an special relation to the first argument, it is explicitly set to be
the format. In the format argument, some characters are special (to printf), for example: valid sequences that start with a
% character and some sequences of backslash-character like:
\\ \a \b \f \n \r \t \v and the special \ddd
So, the string
\n generates a newline but a
$ printf " hi\n hi\\n hi\\\n hi\\\\n"; echo hi hi hi\n hi\n