4

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 C printf commands with respect to the escape character \? And what will I need to put in the variable STRING to obtain the following output on my terminal:

$ printf "${STRING}"
\
$ 
3
  • 1
    I think it's more a matter of what the shell does to (weak quoted) "\\n" before passing it to printf - compare printf '\\\n' for example Jan 23 '18 at 15:43
  • So the shell turns \\\n into \\n, which is fed to printf, which then turns it into \n? Jan 23 '18 at 15:48
  • 1
    Yes 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" Jan 23 '18 at 15:53
4

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"
\
$ 
1
  • Alternatively: With double quotes, put STRING="\\\\\\n". Jan 25 '18 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.