Sample Header Ad - 728x90

How can I assign a heredoc to a variable in a way that's portable across Unix and Mac?

5 votes
3 answers
1138 views
This code works fine on Linux but not Mac OS:
#!/usr/bin/env bash
foo=$(cat <
It fails on Mac with
./test.sh: line 6: unexpected EOF while looking for matching `"'
./test.sh: line 7: syntax error: unexpected end of file
If I do cat < instead of foo=$(cat <, it works fine. Is there a portable way to get heredocs (or multiline strings) into variables without using a file as an intermediate? **Edit**: I want to use a heredoc becuase I have a multiline string with " and '. My actual example looks like:
EXPECTED_ERROR=$(cat <
Asked by Jason Gross (173 rep)
Sep 17, 2024, 02:55 AM
Last activity: Oct 9, 2024, 05:41 PM