Skip to main content
1 of 3
Magnus
  • 1.2k
  • 1
  • 9
  • 14

How to use eval to set variables from a string in linux?

I have a bash script where I'm trying to isolate a string of the form z="y=x" so that I can use eval $z in order to create a env variable y with value 'x'. Here's my code:

xxx=$(terraform state show aws_s3_bucket.prod_bucket | grep website_endpoint | sed 's/ //g')
echo $xxx
>>>website_endpoint="my-site.s3-website-us-east-1.amazonaws.com"
eval $xxx
>>>-bash: website_endpoint=my-site.s3-website-us-east-1.amazonaws.com: command not found

What perplexes me about the failure of this code is that I do something very similar to convert the contents of a .env file to working environment variables:

cmd=$(sed -ne '/^#/d; /^export / {p;d}; /.*=/ s/^/export / p' .env)
eval $cmd     ### works!

Why does the latter work but not the prior?

Magnus
  • 1.2k
  • 1
  • 9
  • 14