Printf example in bash does not create a newline Printf example in bash does not create a newline bash bash

Printf example in bash does not create a newline


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


Maybe people will come here with the same problem I had:echoing \n inside a code wrapped in backsticks. A little tip:

printf "astring\n"# and printf "%s\n" "astring" # both have the same effect.# So... I prefer the less typing one

The short answer is:

# Escape \n correctly !# Using just: printf "$myvar\n" causes this effect inside the backsticks:printf "banana"# So... you must try \\n  that will give you the desired printf "banana\n"# Or even \\\\n if this string is being send to another place # before echoing,buffer="${buffer}\\\\n printf \"$othervar\\\\n\""

One common problem is that if you do inside the code:

echo 'Tomato is nice'

when surrounded with backsticks will produce the error

command Tomato not found.

The workaround is to add another echo -e or printf

printed=0function mecho(){  #First time you need an "echo" in order bash relaxes.  if [[ $printed == 0 ]]; then    printf "echo -e $1\\\\n"    printed=1  else    echo -e "\r\n\r$1\\\\n"  fi}

Now you can debug your code doing in prompt just:

(prompt)$  `mySuperFunction "arg1" "etc"`

The output will be nicely

 mydebug: a value otherdebug: whathever appended using myecho a third string

and debuging internally with

mecho "a string to be hacktyped"


$ printf -v NewLine "\n"$ echo -e "Firstline${NewLine}Lastline"FirstlineLastline$ echo "Firstline${NewLine}Lastline"FirstlineLastline