Rory Hart
Rory Hart

Reputation: 1893

Exporting quoted variables from result of command

I have a command that returns a string with a environment variable in the form of:

foo="foo bar"

The value of foo should be bar not "bar" however I cannot work out how to get bash to play along with exporting this:

$ export `echo 'foo="foo bar"'`
$ env | grep foo
foo="foo bar"

The desired behaviour is:

$ export foo="foo bar"
$ env | grep foo
foo=foo bar

The quotes are needed as variables can have spaces as in the example.

Upvotes: 1

Views: 37

Answers (1)

John1024
John1024

Reputation: 113834

So you have a string such as s:

$ s='foo="bar bar"'

To make and export an environment variable foo while avoiding eval, try:

$ declare -x "${s//\"/}"

We can verify that it worked with:

$ env | grep foo
foo=bar bar

This, of course, assumes that there are no " inside the value of the variable.

Notes:

  1. declare creates a variable assignment as per the supplied string. declare -x both creates and exports the variable.

  2. ${s//\"/} removes all double-quotes from the value of s.

Upvotes: 2

Related Questions