Multi-line string with extra space (preserved indentation)
Heredoc sounds more convenient for this purpose. It is used to send multiple commands to a command interpreter program like ex or cat
cat << EndOfMessageThis is line 1.This is line 2.Line 3.EndOfMessage
The string after <<
indicates where to stop.
To send these lines to a file, use:
cat > $FILE <<- EOMLine 1.Line 2.EOM
You could also store these lines to a variable:
read -r -d '' VAR << EOMThis is line 1.This is line 2.Line 3.EOM
This stores the lines to the variable named VAR
.
When printing, remember the quotes around the variable otherwise you won't see the newline characters.
echo "$VAR"
Even better, you can use indentation to make it stand out more in your code. This time just add a -
after <<
to stop the tabs from appearing.
read -r -d '' VAR <<- EOM This is line 1. This is line 2. Line 3.EOM
But then you must use tabs, not spaces, for indentation in your code.
If you're trying to get the string into a variable, another easy way is something like this:
USAGE=$(cat <<-END This is line one. This is line two. This is line three.END)
If you indent your string with tabs (i.e., '\t'), the indentation will be stripped out. If you indent with spaces, the indentation will be left in.
NOTE: It is significant that the last closing parenthesis is on another line. The END
text must appear on a line by itself.
echo
adds spaces between the arguments passed to it. $text
is subject to variable expansion and word splitting, so your echo
command is equivalent to:
echo -e "this" "is" "line" "one\n" "this" "is" "line" "two\n" ...
You can see that a space will be added before "this". You can either remove the newline characters, and quote $text
to preserve the newlines:
text="this is line onethis is line twothis is line three"echo "$text" > filename
Or you could use printf
, which is more robust and portable than echo
:
printf "%s\n" "this is line one" "this is line two" "this is line three" > filename
In bash
, which supports brace expansion, you could even do:
printf "%s\n" "this is line "{one,two,three} > filename