Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash variable- embedded newline at end of variable

Tags:

bash

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.

like image 451
Mike S Avatar asked Aug 31 '15 18:08

Mike S


People also ask

How do I add a new line to the end of a string?

Adding Newline Characters in a String In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

What is $# in bash?

$# shows the number of the script's arguments $? shows the last script's return value. about arguments: echo "ARG[$#]" before if and then execute the script like script.sh 1.

Can environment variables have newlines?

In order to save an environment variable with newlines, the variable can be base64 encoded before saving and then unencoded during the CircleCI build.


1 Answers

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.

like image 186
Etan Reisner Avatar answered Nov 09 '22 09:11

Etan Reisner