Shell Variable Names – Can Variable Names Include a Hyphen or Dash?

environment-variablesshell

I am not able to use - in variables in shell. Is there a way to be able to use it, because I have one script which depends on such named variables:

$export a-b=c
-bash: export: `a-b=c': not a valid identifier

$export a_b=c

First throws the given error and second works fine.

Best Answer

I've never met a Bourne-style shell that allowed - in a variable name. Only ASCII letters (of either case), _ and digits are supported, and the first character must not be a digit.

If you have a program that requires an environment variable that doesn't match the shell restrictions, launch it with the env program.

env 'strange-name=some value' myprogram

Note that some shells (e.g. modern dash, mksh, zsh) remove variables whose name they don't like from the environment. (Shellshock has caused people to be more cautious about environment variable names, so restrictions are likely to become tighter over time, not more permissive.) So if you need to pass a variable whose name contains special character to a program, pass it directly, without a shell in between (env 'strange-name=some value' sh -c'…; myprogram' may or may not work).

Related Question