Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set environment variables with a forward slash in the key

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.

like image 270
bromanko Avatar asked Jun 09 '15 02:06

bromanko


People also ask

How do you set environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.

What characters are allowed in environment variables?

Only uppercase letters, lowercase letters, and underscores from this character set are allowed.

How do you escape a forward slash in bash?

A non-quoted backslash ' \ ' is the Bash escape character. It preserves the literal value of the next character that follows, with the exception of newline .

Can environment variables have dots?

It is not possible to set environment variables with dots in their name. If you try to set one in the UI, it just does not work without error message.


2 Answers

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
like image 62
chepner Avatar answered Oct 16 '22 18:10

chepner


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.)

like image 35
John1024 Avatar answered Oct 16 '22 17:10

John1024