Assign Here Document Facility to a Variable

Hello All,

I was wondering how I can assign a here document facility to a variable. I have tried the following:

menu=$(<<MENU
Option1
Option2
Option3
Option4
MENU
)

...but when I echo the $menu variable, the multiline list comes out in a single line such as:

Option1 Option2 Option3 Option4

How can I have it maintain the multiline list such as the following?:

Option1
Option2
Option3
Option4

Thanx

You should use:

menu=$(cat <<MENU...

But in this case you could just do:

menu="Option1
Option2
Option3
Option4"

When printing the content, don't forget to quote the variable to prevent field splitting:

$ printf "%s\n" "$menu"
Option1
Option2
Option3
Option4

Thanx for the response, I tried the suggested $(cat <<MENU... but that made no difference and the other option does not provide the needed solution. I am really hoping that the here document has a tweak for this.

Did you read the rest of my post?

Yes, I read it, which is what I responded to when I said it wasn't what I was looking for and really need to get the here document to work.

And did you try the very last bit about how to print a variable?

It displays the options and I am able to center it but just not left justified as can be accomplished with Here document.

---------- Post updated 05-07-13 at 12:00 AM ---------- Previous update was 05-06-13 at 05:25 PM ----------

I stand corrected, it works just fine. I appreciate it.

Hi, good. You can still use a here doc if you want and put it into a variable, but when subsequently using that variable you need to quote it to retain formatting...

Okay, I will give that a shot.

what is the difference between using

$(cat <<MENU...

&

$(<<MENU...

The first form works, AFAIK the latter does not.

I've tested both variants successfully using the korn shell.

Indeed it seems to work in ksh and ksh derivatives (for example the posix shells in Solaris and HPUX which are modified Korn shells). It also seems to work in zsh.

But is does not work in bash, nor in POSIX compliant dash, so I would use the cat form..

My question would be, why bother?

Particularly when this is valid syntax:

MYVAR="string1
string2
string3
string4
string5"

It could be used to avoid certain quoting issues...