mikezter
mikezter

Reputation: 2463

Exporting an env-file with values containing space

I'm using environment files to configure web apps. Recently i had the need to export a value like this:

RUBYOPT='-W:no-derecated -W:no-experimental'

This is contained in a file test.env with other config vars.

I use this command to export all the env vars in the file:

export $(cat test.env | xargs)

With the value like above, the command gives this error:

-bash: export: `-W:no-experimental'': not a valid identifier

I can export the value by copy pasting the output of cat test.env | xargs but in a single command like above it doesnt work.

Some testing revealed, that the issue appears when the value contains a space and somewhere after that a colon :.

What kind of quotation sorcery do I need to make my env-file work again?

Upvotes: 6

Views: 5275

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

The construct with export $(cat test.env | xargs) is very fragile and you get shell interpretation of the ' characters (and other special characters) so RUBYOPT='-W:no-derecated -W:no-experimental' therefore becomes RUBYOPT=-W:no-derecated -W:no-experimental. Note the missing '. This was not a problem until you set variables with space in them.

I recommend dropping this way of exporting all variables in the environment file.

If your test.env file contains assignments to variables in bash syntax, that are not exported, you could instead turn on automatic exporting and then source the test.env file.

Example:

set -a      # turn on automatic exporting
. test.env  # source test.env
set +a      # turn off automatic exporting

From BASH_BUILTINS (man set):

set -a "Each variable or function that is created or modified is given the export attribute and marked for export to the environment of subsequent commands."

Upvotes: 15

Related Questions