Bash – Printf example in bash does not create a newline

bashprintf

Working with printf in a bash script, adding no spaces after "\n" does not create a newline, whereas adding a space creates a newline, e. g.:

  1. No space after "\n"

    NewLine=`printf "\n"`
    echo -e "Firstline${NewLine}Lastline"
    

    Result:

    FirstlineLastline
    
  2. Space after "\n "

    NewLine=`printf "\n "`
    echo -e "Firstline${NewLine}Lastline"
    

    Result:

    Firstline
     Lastline
    

Question: Why doesn't 1. create the following result:

Firstline 
Lastline

I know that this specific issue could have been worked around using other techniques, but I want to focus on why 1. does not work.

Edited:
When using echo instead of printf, I get the expected result, but why does printf work differently?

    NewLine=`echo "\n"`
    echo -e "Firstline${NewLine}Lastline"

Result:

    Firstline
    Lastline

Best Answer

The backtick operator removes trailing new lines. See 3.4.5. Command substitution at http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html

Note on edited question

Compare:

[alvaro@localhost ~]$ printf "\n"

[alvaro@localhost ~]$ echo "\n"
\n
[alvaro@localhost ~]$ echo -e "\n"


[alvaro@localhost ~]$

The echo command doesn't treat \n as a newline unless you tell him to do so:

NAME
       echo - display a line of text
[...]
       -e     enable interpretation of backslash escapes

POSIX 7 specifies this behaviour here:

[...] with the standard output of the command, removing sequences of one or more characters at the end of the substitution