Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

\n in variable in heredoc

Is there any way to for a Bash heredoc to interpret '\n\' in a heredoc?

I have an iteratively built string in a loop, something like

for i in word1 word2 word3
do
        TMP_VAR=$i
        ret="$ret\n$TMP_VAR"
done

and then I want to use the created string in a heredoc:

cat <<EOF > myfile
HEADER
==
$ret
==
TRAILER
EOF

however I would like to interpret the "\n" character as newline, so that the output is

HEADER
==
word1
word2
word3
==
TRAILER

instead of

HEADER
==
\nword1\nword2\nword3
==
TRAILER

Is it possible? Or should I perhaps build my initial string somehow otherwise?

like image 471
Kamil Roman Avatar asked Jan 22 '15 13:01

Kamil Roman


People also ask

What is Heredoc delimiter?

Heredoc uses 2 angle brackets (<<) followed by a delimiter token. The same delimiter token will be used to terminate the block of code. Whatever comes within the delimiter is considered to be a block of code.

Which symbol is used for creating Heredoc?

The most common syntax for here documents, originating in Unix shells, is << followed by a delimiting identifier (often the word EOF or END), followed, starting on the next line, by the text to be quoted, and then closed by the same delimiting identifier on its own line.

How do I end Heredoc?

To use here-document in any bash script, you have to use the symbol << followed by any delimiting identifier after any bash command and close the HereDoc by using the same delimiting identifier at the end of the text.

What is Heredoc zsh?

In bash and other shells such as zsh, ksh, etc a Here document (Heredoc) is a type of redirection that allows you to pass multiple lines of input to a command or script. If a programmer needs less amount of text data then using code and data in the same file is a better option it can be done easily using heredoc.


2 Answers

In bash you can use $'\n' to add a newline to a string:

ret="$ret"$'\n'"$TMP_VAR"

You can also use += to append to a string:

ret+=$'\n'"$TMP_VAR"
like image 106
Tom Fenech Avatar answered Oct 04 '22 10:10

Tom Fenech


As others (and other answers to other questions) have said, you can put encoded characters into a string for the shell to interpret.

x=$'\n' # newline
printf -v x '\n' # newline

That said, I don't believe there is any way to directly put an encoded newline into a heredoc.

cat <<EOF
\n
EOF

just outputs a literal \n

cat <<$'EOF'
…
EOF

is nothing special, nor is <<'EOF'

The best you can do is to preencode the newline, and include the expansion in the heredoc:

nl=$'\n'
cat <<EOF
foo bar $nl baz
EOF

outputs

foo bar
 baz
like image 45
kojiro Avatar answered Oct 04 '22 12:10

kojiro