11

I know that you can create environment variables with the command env.

For example:

env A.B=D bash

The problem is for env a command is required thus creating a new subprocess.

Cœur
  • 37,241
  • 25
  • 195
  • 267
razpeitia
  • 1,947
  • 4
  • 16
  • 36
  • 1
    Whatever program `env` starts reuses the same process (that is, `env` calls `exec` to replace itself with the program it runs). – chepner Apr 20 '15 at 17:41

2 Answers2

14

Bash does not allow environment variables with non-alphanumeric characters in their names (aside from _). While the environment may contain a line such as A.B=D, there is no requirement that a shell be able to make use of it, and bash will not. Other shells may be more flexible.

Utilities which make use of oddly-named environment variables are discouraged, but some may exist. You will need to use env to create such an environment variable. You could avoid the subprocess with exec env bash but it won't save you much in the way of time or resources.

rici
  • 234,347
  • 28
  • 237
  • 341
  • This bash restriction is documented in the definition of `name`: https://www.gnu.org/software/bash/manual/bashref.html#Definitions – glenn jackman Apr 20 '15 at 16:31
6

rici has the correct answer. To demonstrate the difference required to access such environment entries, bash requires you to parse the environment as text:

$ env A.B=C perl -E 'say $ENV{"A.B"}'
C
$ env A.B=C bash -c 'val=$(env | grep -oP "^A\.B=\K.*"); echo "$val"'
C
glenn jackman
  • 238,783
  • 38
  • 220
  • 352