I am planning to use(hyphen -) in a variable test-ing=3.0 but I am unable to print value $test-ing. I know hyphen will not work on shell, any possible way to print the variable value without changing the variable name?
-
1This seems like a terrible idea. (Why don't you throw in a backslash and a dollar sign for good measure ;-) ?) The older one gets the more important appears to become portability.Peter - Reinstate Monica– Peter - Reinstate Monica2020-01-23 17:46:28 +00:00Commented Jan 23, 2020 at 17:46
-
@Peter-ReinstateMonica Agreed. Let's have a car analogy: How to use custard (pudding) instead of lugnuts? I have to wonder what's driving the decision not to change the variable name ... sunk cost fallacy, p'raps?Rich– Rich2020-01-23 18:48:46 +00:00Commented Jan 23, 2020 at 18:48
-
1Save yourself tons of troubles and use underscores instead, that's what they're for.maaartinus– maaartinus2020-01-24 01:09:18 +00:00Commented Jan 24, 2020 at 1:09
2 Answers
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.
-
1
-
6Beware though that some shells like
mkshremove from the environment the variables that can't be mapped to shell variables (tryenv foo-bar=baz mksh -c 'printenv foo-bar'for instance). So use at your own risk and be prepared for those not to traverse allexec()chains.Stéphane Chazelas– Stéphane Chazelas2020-01-23 07:54:54 +00:00Commented Jan 23, 2020 at 7:54
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.