Mike S
Mike S

Reputation: 1371

Bash variable- embedded newline at end of variable

I have read Trying to embed newline in a variable in bash and I think I understand about the newline as the IFS, and how bash changes newlines into spaces at times, but I don't understand this situation:

[prompt]$ blah="$(printf "hi\n\n\n\n")"
[prompt]$ echo "$blah"
hi
[prompt]$ blah="$(printf "hi\n\n\n\nx")"
[prompt]$ echo "$blah"
hi



x

Why did the first echo not spit out a bunch of newlines? Thanks.

Upvotes: 6

Views: 227

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 81052

Because that's what the spec says the shell should do. Namely strip trailing sequences of newlines.

From the spec (emphasis mine):

The shell shall expand the command substitution by executing command in a subshell environment (see Shell Execution Environment) and replacing the command substitution (the text of command plus the enclosing "$()" or backquotes) with the standard output of the command, removing sequences of one or more newline characters at the end of the substitution. Embedded newline characters before the end of the output shall not be removed; however, they may be treated as field delimiters and eliminated during field splitting, depending on the value of IFS and quoting that is in effect. If the output contains any null bytes, the behavior is unspecified.

Upvotes: 6

Related Questions