7

Is there a way to export an environment variable with a slash in the name such as:

export /myapp/db/username=someval

This post indicates it should be possible but I cannot figure out valid syntax to do so.

For background:

I am using confd to produce config files from a template and key store. The typical stores (consul, etcd) use hierarchical keys such as /myapp/db/username. I would like to transparently allow for switching between using an environment variable based provider and a configuration store that leverages hierarchical keys.

stefanobaghino
  • 11,253
  • 4
  • 35
  • 63
bromanko
  • 928
  • 1
  • 9
  • 15
  • I would normally suggest use of an associative array. `declare -A a; a[/myapp/db/username]=someval`. Only problem is that arrays cannot be exported. – anishsane Jun 09 '15 at 06:41

2 Answers2

4

Yes, you can export such an environment variable but not from a bash export statement.

While bash will refuse to create an environment variable named, for example, a/b, we can create it with python and subshells created by python will see it.

As an example, consider the following python command:

$ python -c 'import os; os.environ["a/b"]="2"; os.system("/bin/bash");'

If we run this command, we are put into a subshell. From that subshell, we can see that the creation of the environment variable was successful:

$ printenv | grep a/b
a/b=2

(At this point, one may want to exit the subshell (type exit or ctrl-D) to return to the python program which will exit and return us to the main shell.)

John1024
  • 109,961
  • 14
  • 137
  • 171
4

export only marks valid shell identifiers to be exported into the environment, not any string that could form a valid name/value pair in the environment. You can use env to create a new shell instance with such an environment, though.

env "/myapp/db/username=someval" bash
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Very interesting, I didn't know this was possible. How would you reference such a variable from the shell, though? `${/myapp/db/username}` gets confused for bad substitution, and there doesn't appear to be a special array that contains environment variables. – ghoti Jun 09 '15 at 12:47
  • You can't. The shell can only interface with the environment through the lens of shell variables. It can only read from and write to the environment strings of the form `NAME=VALUE` where `NAME` is a valid shell identifier and `VALUE` may be optionally empty. There would be no reason for the shell to require broader support, because the only reason to add other kinds of strings would be for the benefit of a new program, but you can do that via `env`. – chepner Jun 09 '15 at 13:00