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
答案 0 :(得分: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.