1

This question already has an answer here:

I am trying to make use of the solution presented in one of the answers of https://stackoverflow.com/questions/1167746/how-to-assign-a-heredoc-value-to-a-variable-in-bash

In Bash version 4.2.47(1)-release when I execute the following code it prematurely exits because read fails when it encounters EOF:

shopt -os errexit

function foobar {
    local desc=
    read -d '' -r desc <<EOF
bla bla
EOF
    echo "$desc"
}

In order to return success if read fails at EOF I have rewritten the line as read -d '' -r desc || true <<EOF but now the script indefinitely waits.

Do you know how to make this code work?

marked as duplicate by jw013, slm, jasonwryan, vonbrand, derobert Jun 20 '14 at 7:18

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • desc=$(cat <<HERE\nbla bla\nHERE\n) or desc='\nbla bla\n ' – mikeserv Jun 19 '14 at 22:33
  • An external command such as cat is always an alternative but I prefer to use Bash built-in's wherever possible. Also inserting \n at the end of each line is not an option for me since my actual text is around 50 lines long. – Tim Friske Jun 19 '14 at 22:48
  • I only did that for the sake of the comments - because otherwise you can't tell. If you want you could just do: desc= ; : <<HERE\n${desc:=\nbla bla\n}\nHERE\n Each \n should stand in for an actual \newline character. I think you'll find, though, that many of bashisms probably call on cat and similar anyway. The one invocation to declare a single 50 line var should not be taxing in anyway. I also think this works in bash, but I'm not sure: desc=$(<<HERE\n...\nHERE\n) – mikeserv Jun 19 '14 at 22:52
  • See unix.stackexchange.com/q/13272/9537. What you want is read ... <<EOF || true not read ... || true <<EOF. The <<EOF is for the read not the true. I assume your actual code is a bit more complex than your toy example, because in this case assigning to the variable directly would be much simpler. – jw013 Jun 19 '14 at 23:09
  • @jw013 - the contents of the <<HEREDOCUMENT must be read in the first place in order for it to exist at all. Why not just set the variable as a consequence of that action rather using two actions - and calling the external true application besides? At the very least OP should use || : instead - at least it is guaranteed as a builtin. – mikeserv Jun 20 '14 at 0:11