Skip to content

Instantly share code, notes, and snippets.

@adamelliotfields
Created May 20, 2025 12:31
Show Gist options
  • Save adamelliotfields/aee3d04fea2f020dc8abb7f4f6d41463 to your computer and use it in GitHub Desktop.
Save adamelliotfields/aee3d04fea2f020dc8abb7f4f6d41463 to your computer and use it in GitHub Desktop.
Assign heredoc to variable in Bash

Instead of concatenation:

str=""
str+="This is a\n"
str+="multiline string"

You can use a heredoc:

cat <<EOF
This is a
multiline string
EOF

However, heredocs are meant for standard input. To store in a variable, you need a command that reads from standard input and assigns it.

That's what read does:

read -r -d '' str <<EOF
This is a
multiline string
EOF

The -r flag prevents backslash escapes from being interpreted, and the -d '' flag means read until EOF (empty delimiter).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment