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.:
-
No space after
"\n"
NewLine=`printf "\n"` echo -e "Firstline${NewLine}Lastline"
Result:
FirstlineLastline
-
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:
The echo command doesn't treat
\n
as a newline unless you tell him to do so:POSIX 7 specifies this behaviour here: