Printf example in bash does not create a newline

前端 未结 8 1730
臣服心动
臣服心动 2020-12-09 08:20

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.:

8条回答
  •  猫巷女王i
    2020-12-09 08:31

    Your edited echo version is putting a literal backslash-n into the variable $NewLine which then gets interpreted by your echo -e. If you did this instead:

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

    your result would be the same as in case #1. To make that one work that way, you'd have to escape the backslash and put the whole thing in single quotes:

    NewLine=$(printf '\\n')
    echo -e "Firstline${NewLine}Lastline"
    

    or double escape it:

    NewLine=$(printf "\\\n")
    

    Of course, you could just use printf directly or you can set your NewLine value like this:

    printf "Firstline\nLastline\n"
    

    or

    NewLine=$'\n'
    echo "Firstline${NewLine}Lastline"    # no need for -e
    

提交回复
热议问题