0

So while i was testing a python program i have been working on i noticed that echo -e "\n" and printf "\n" according to the if statement in bash.

Even though echo -e "\n" prints two newlines (it appends one by default) and printf only prints one.

if [ "$(echo -e "\n")" == "$(printf "\n")" ]
then
    echo 1
fi

and

if [ $(echo -e "\n") -eq $(printf "\n") ]
then
    echo 1
fi

both outputs 1 in bash. I have also noticed that assigning the outputs to an variable only outputs a single newline for both echo -e "\n" and printf "\n",

A=$(echo -e "\n")
B=$(printf "\n")

echo $A # outputs a single newline
echo $B # also outputs a single newline

so i am thinking that echo might output the newline differently with fx. stderr?

1 Answer 1

2

The newlines are deleted by the command substitution $(). The manpage of bash says:

Command substitution allows the output of a command to replace the command name. There are two forms:

$(command)

or

`command`

Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

1
  • @JavadSM BTW, even if $( ) didn't remove the newlines, if it's unquoted the shell will treat those newlines as whitespace and ignore them. Thus, [ $(echo -e "\n") -eq $(printf "\n") ] parses down to the equivalent of [ -eq ], which is true because "-eq" is not the null string. [ $(echo -e "\n") -ne $(printf "\n") ] and [ $(echo -e "\n") wibble $(printf "\n") ] will give the same result for the same reason. Moral: use double-quotes around pretty much all command and variable expansions to avoid parsing weirdness. Feb 14, 2018 at 4:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .