kkyr
kkyr

Reputation: 3845

Bash/Zsh - Export environment variable with name containing a colon

I'm trying to set the following environment variable in bash:

ConnectionStrings:DefaultConnection=someValue

I'm using the following command:

export ConnectionStrings:DefaultConnection=something

In bash I get the following error:

export: 'ConnectionStrings:DefaultConnection=something': not a valid identifier

And in zsh the following error:

export: not valid in this context: ConnectionStrings:DefaultConnection

How can I set an environment variable whose variable name contains a colon?

Upvotes: 4

Views: 5233

Answers (1)

John1024
John1024

Reputation: 113994

Bash doesn't support such names but you can create them with external programs like env or python.

Using env

The command env will set an environment and run another command. For example, here we use env to run printenv:

$ env a:b=3 printenv | grep ^a
a:b=3

env can also be used to run a new shell:

$ env a:b=4 bash
$ printenv | grep ^a
a:b=4

(Hat tip: Chepner).

Using python

Python allows manipulation of the environment. This python script creates environment variables with colons and then runs an instance of bash:

$ cat colon.py
#!/bin/python 
import os
import subprocess
os.environ['a:b'] = 'c'
os.environ['ConnectionStrings:DefaultConnection'] = 'someValue'
subprocess.call('bash')

If we run the above script, we will get a new bash prompt. At the new prompt, we can verify that the variables exist:

$ printenv | grep -E 'Connection|a:b'
ConnectionStrings:DefaultConnection=someValue
a:b=c

Environment variable names that bash supports

Unless one has a very good reason to want nonconforming variable names, it is much easier to use variable names that bash supports. That would include names that start with a letter or underline followed by zero or more alphanumeric characters or underlines.

Upvotes: 6

Related Questions