How do I print backslash followed by newline with printf?
In your snippet below, you use "double quotes" around the backslash escapes:
$ STRING="\\\n"
$ printf "${STRING}"
\n$
However, Bash still evaluates some backslash-escapes inside double quotes, so the content of your variable after that is really \\n
, as "\\"
evaluates to \
.
Put the string in 'single quotes' to prevent the shell from touching any of the backslashes:
$ STRING='\\\n'
$ printf "$STRING"
\
$
Related videos on Youtube
Jonas Dahlbæk
Updated on September 18, 2022Comments
-
Jonas Dahlbæk almost 2 years
Using Python, I get
$ python3 -c 'print("\\\n")' \ $
That is, one backslash and one newline, followed by an extra newline inserted by the interpreter.
Using C, compiling the code
#include <stdio.h> int main(void) { printf("\\\n"); return 0; }
into a file
backslash.out
yields$ ./backslash.out \ $
That is, one backslash and one newline.
In bash, I get
$ STRING="\\\n" $ printf "${STRING}" \n$
What exactly is the bash printf command doing here? What is it doing differently from the python
print
or Cprintf
commands with respect to the escape character\
? And what will I need to put in the variableSTRING
to obtain the following output on my terminal:$ printf "${STRING}" \ $
-
steeldriver over 6 yearsI think it's more a matter of what the shell does to (weak quoted)
"\\n"
before passing it toprintf
- compareprintf '\\\n'
for example -
Jonas Dahlbæk over 6 yearsSo the shell turns
\\\n
into\\n
, which is fed toprintf
, which then turns it into\n
? -
steeldriver over 6 yearsYes sorry I meant
"\\\n"
- if you want to use a variable, then try hard-quoting the string and then using printf's%b
format:string='\\\n' ; printf '%b' "$string"
-
-
Jonas Dahlbæk over 6 yearsAlternatively: With double quotes, put
STRING="\\\\\\n"
.