How do I print backslash followed by newline with printf?

5,402

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"
\
$ 
Share:
5,402

Related videos on Youtube

Jonas Dahlbæk
Author by

Jonas Dahlbæk

Updated on September 18, 2022

Comments

  • Jonas Dahlbæk
    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 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}"
    \
    $ 
    
    • steeldriver
      steeldriver over 6 years
      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
    • Jonas Dahlbæk
      Jonas Dahlbæk over 6 years
      So the shell turns \\\n into \\n, which is fed to printf, which then turns it into \n?
    • steeldriver
      steeldriver over 6 years
      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"
  • Jonas Dahlbæk
    Jonas Dahlbæk over 6 years
    Alternatively: With double quotes, put STRING="\\\\\\n".