-1

I would like to achieve this in Bash: echo $(a=1)and print the value of variable a

I test eval, $$a,{}, $() but none of them work as most of the times either I got literally a=1 or in one case (I don't remember which) it tried to execute the value.

I known that I can do: a=1;echo $a but because I'm little fun one command per line (even if sometimes is getting little complicated) I was wondering if is possible to do this either with echo or with printf

Alex
  • 39
  • 1
  • 1
  • 5

1 Answers1

3

If you know that $a is previously unset, you can do this using the following syntax:

echo ${a:=1}

This, and other types of parameter expansion, are defined in the POSIX shell command language specification.

If you want to assign a numeric value, another option, which doesn't depend on the value previously being unset, would be to use an arithmetic expansion:

echo $(( a = 1 ))

This assigns the value and echoes the number that has been assigned.

It's worth mentioning that what you're trying to do cannot be done in a subshell by design because a child process cannot modify the environment of its parent.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • The second I saw it also but if I will use this way (the all in one command) probably it will be a string. The first if I don't use `unset` makes it useful once. :( – Alex Apr 04 '16 at 18:07
  • You probably want `echo ${a:-1}`, which uses `1` for the expansion if `a` is unset (or set to the empty string), but doesn't set (or change) the value of `a`. – chepner Apr 04 '16 at 18:28
  • @chepner I was under the impression that the intent was to assign a new value to `$a` as well as print the new value (but I'm not 100%) – Tom Fenech Apr 04 '16 at 18:29
  • @TomFenech I think I'm misinterpreting his comment above. – chepner Apr 04 '16 at 18:30
  • @TomFenech yes, this is what I would like. – Alex Apr 04 '16 at 18:46
  • @Alex I'm afraid I don't think there's a way of doing what you're trying to do in a single statement. – Tom Fenech Apr 04 '16 at 20:11
  • @TomFenech Probably. It was a long shot but you never know. – Alex Apr 05 '16 at 16:44