0

I want to set FOO="myvar" and set myvar to another variable. Not sure if that makes sense. Example below.

FOO="myvar"
BAR="true true false"
eval $FOO=$BAR    <==== Problem line
echo $myvar

I want the last line to print "true true false"

EncryptedWatermelon
  • 4,788
  • 1
  • 12
  • 28
  • 1) `$mayvar` isn't defined anywhere .. 2) if this is straight `bash` -- lose the `eval $` and just set `FOO=$BAR` if you are in fact trying to set `FOO = BAR` or in plain words *FOO is equal to BAR* – Zak Sep 04 '19 at 15:46
  • myvar is the string in $FOO. I want to create a variable with the name of $FOO with the contents of $BAR – EncryptedWatermelon Sep 04 '19 at 15:49
  • then should you no be echoing `$FOO` -- NOT `$myvar` (which is a string not a variable name)? I am confused. – Zak Sep 04 '19 at 15:51
  • 2
    `echo "${!myvar}"` is an indirect lookup. Which we already have existing Q&A for. – Charles Duffy Sep 04 '19 at 15:53
  • @Zak `eval $FOO=$BAR` expands to `eval myvar=true true false`, which, if quoted properly, would then perform the desired assignment to the name `myvar`. – chepner Sep 04 '19 at 15:53
  • I want FOO to be expanded to myvar. I then want to set myvar equal to bar. "myvar" is passed into a function and I don't know when it is in advance. – EncryptedWatermelon Sep 04 '19 at 15:54
  • @EncryptedWatermelon, yes, that's indirect assignment and expansion. Look under that name and you'll find *lots* of entries already in the knowledgebase. – Charles Duffy Sep 04 '19 at 15:54
  • 1
    ...it's also very extensively documented in [BashFAQ #6](http://mywiki.wooledge.org/BashFAQ/006). – Charles Duffy Sep 04 '19 at 15:55
  • 1
    @EncryptedWatermelon, ...btw, see [BashFAQ #48](https://mywiki.wooledge.org/BashFAQ/048) re: why answers using `eval` are frowned on. (It's *possible* to use safely, but requires a lot of care both when writing and when auditing code for security, which is why newer/safer constructs are preferred instead). – Charles Duffy Sep 04 '19 at 15:56
  • Much appreciated. I had no idea what it was called. – EncryptedWatermelon Sep 04 '19 at 15:59
  • (btw, (1) all-caps variable names are used for variables meaningful to the shell and OS, whereas names with at least one lowercase character are reserved for application use and guaranteed not to conflict -- see https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html, keeping in mind that environment and shell variables share a namespace; (2) if `true true false` is meant to be a list of separate items, it's generally good practice to use an array instead of a string). – Charles Duffy Sep 04 '19 at 16:00

0 Answers0