4

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?

  • 1
    This 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 Jan 23 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 Jan 23 at 18:48
  • 1
    Save yourself tons of troubles and use underscores instead, that's what they're for. – maaartinus Jan 24 at 1:09
11

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
    ENVIRON array in awk also – Inian Jan 23 at 7:01
  • 6
    Beware though that some shells like mksh remove from the environment the variables that can't be mapped to shell variables (try env foo-bar=baz mksh -c 'printenv foo-bar' for instance). So use at your own risk and be prepared for those not to traverse all exec() chains. – Stéphane Chazelas Jan 23 at 7:54
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.