Contents
How to put newlines in quotes in Bash?
You can put literal newlines within single quotes (in any Bourne/POSIX-style shell). For a multiline string, here documents are often convenient. The string is fed as input to a command. If you want to store the string in a variable, use the cat command in a command substitution.
When do you add a new line to a quote?
So long as the total number of quote characters encountered is odd, a line is appended to its predecessor. When finally an even number of quote characters have been seen, the resulting concatenation of lines is printed, with all embedded newlines converted to spaces.
When to replace a new line with a space?
Here’s a solution that only replaces a newline with a space when that newline occurs between an opening quote character and its corresponding close quote. So long as the total number of quote characters encountered is odd, a line is appended to its predecessor.
Why are newlines replaced with spaces in Bash?
The reason why newlines are replaced with spaces is not entirely to do with the echo command, rather it’s a combination of things. When given a command line, bash splits it into words according to the documentation for the IFS variable:
Do you have to use another line in Bash?
Another pitfall with this is that command substitution — $ () — strips trailing newlines. Probably not always important, but if you really want to preserve exactly what was output, you’ll have to use another line and some quoting:
How to remove newlines from a string in Bash?
The newline character (s) at the end of the string will be stripped by the command substitution. If you want to retain the final newlines, put a stopper at the end and strip it away afterward.
How does multiple line output work in Bash?
Thus (1) preserves the shape of the input variable, whereas (2) creates a potentially very long single line of output with ‘words’ separated by single spaces (where a ‘word’ is a sequence of non-whitespace characters; there needn’t be any alphanumerics in any of the words).