Search code examples
bashawkeval

using Eval to set variable equal to multiple line string


I am trying to use eval to set a multiline variable

$ k="A
B
C"

$ echo "$k"
A
B
C

$ eval 'k="1
2
3"'

$ echo "$k"
1
2
3

But I want to use awk to produce my variable with an awk script

$ echo "$k" | awk 'BEGIN{RS="";FS="[ \t]+"}{print "awkV=\""$0"\""}' 
awkV="1
2
3"

$ eval `echo "$k" | awk 'BEGIN{RS="";FS="[ \t]+"}{print "awkV=\""$0"\""}'`
$ echo "$awkV"
1 2 3

$ eval '`echo "$k" | awk 'BEGIN{RS="";FS="[ \t]+"}{print "awkV=\""$0"\""}'`'
-bash: unexpected EOF while looking for matching ``'
-bash: syntax error: unexpected end of file
bash: awkV="-bash"}`: command not found...

I need to put some sort of quote around the eval statement, but I am using both single and double quotes internally and single quoting will probably mess up the "$k" I am using inside the script as well. I tried putting the executed code in a heredoc without success, though maybe I am doing that wrong.

Help and suggestions would be appreciated.

Note this is just a minimal example of the problem and not my full application.


Solution

  • Reusing your awk script as-is and assuming you do have a good reason for wanting to do this:

    $ eval "$(echo "$k" | awk 'BEGIN{RS="";FS="[ \t]+"}{print "awkV=\""$0"\""}')"
    

    $ echo "$awkV"
    A
    B
    C
    

    See https://mywiki.wooledge.org/BashFAQ/082 for this and other reasons to use command substitution with $(...) instead of the old, fragile, quirky backticks.