Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading