How to use (- Hyphen) in a variable name in shell?
Assuming an environment variable, since test-ing
is not a valid shell variable name, you can use printenv
:
% env foo-bar=baz printenv foo-bar
baz
Or Perl:
% env foo-bar=baz perl -e 'print $ENV{"foo-bar"}'
baz
Or other tools like Python, etc.
In the rc
shell or derivatives (es
, akanga
), just about anything can be used in a variable name.
All variables are also exported to the environment.
However, in Byron Rakitzis' clone of rc
for Unix (from which es
/akanga
derive), as opposed to the port of plan9 rc
(now publicly available since plan9 has been released as FLOSS), note that for those that contain characters outside of a-zA-Z0-9_
or sequences of two or more underscores, an encoding/decoding is used upon export/import from the environment:
$ rc
; foo-bar = baz
; echo $'foo-bar'
baz
; printenv foo-bar
; env | grep foo
foo__2dbar=baz
In Byron's rc
, one also can't use a variable with an empty name:
; '' = 1
rc: zero-length variable name
Things like 1 = foo
or * = (foo bar)
work, but they set the positional parameters, not variables.