Home > database >  How can you append to a bash array of strings with heredoc
How can you append to a bash array of strings with heredoc

Time:02-19

I need to create a bunch of strings using heredocs which I want to store in an array so that I can run them all through processes later. For example

IFS='' read -r -d '' data  << END
{
"my": "first doc"
}
END

IFS='' read -r -d '' data  << END
{
"my": "second doc"
}
END

I know I could append to an array of docs using a construction like

docs =("${data}")

after each heredoc, but is there a slick way I can do it directly in the read command without assigning index values (so I can change the order, add others in the middle, etc without it being awkward)?

CodePudding user response:

The easy approach is to build a function that uses namevars to refer to your destination array indirectly.

Note that namevars are a feature added in bash 4.3; before that release, it's not as easy to have the variable be parameterized without getting into unpleasantries like eval, so you might end up just hardcoding data as your destination if you want portability (and that makes sense in the context at hand).

append_to_array() {
  declare -n _dest="$1"
  _dest =( "$(</dev/stdin)" )
}

append_to_array data <<'END'
{
"my": "first doc"
}
END

append_to_array data <<'END'
{
"my": "second doc"
}
END

See this running at https://ideone.com/9zEMWs

  • Related