Bash variable assignment not working expected

2020-05-08 10:01发布

问题:

status=0
$status=1

echo $status

Can anyone tell my what i am doing wrong with this?

It gives me the following error:

 0=1: command not found

回答1:

This line is OK - it assigns the value 0 to the variable status:

status=0

This is wrong:

$status=1

By putting a $ in front of the variable name you are dereferencing it, i.e. getting its value, which in this case is 0. In other words, bash is expanding what you wrote to:

0=1

Which makes no sense, hence the error.

If your intent is to reassign a new value 1 to the status variable, then just do it the same as the original assignment:

status=1


回答2:

Bash assignments can't have a dollar in front. Variable replacements in bash are like macro expansions in C; they occur before any parsing. For example, this horrible thing works:

foof="[ -f"
if $foof .bashrc ] ; then echo "hey"; fi


回答3:

Only use the $ when actually using the variable in bash. Omit it when assigning or re-assining.

e.g.

status=0
status2=1
status="$status2"


回答4:

also this ugly thing works too :

status='a'
eval $status=1

echo $a 
1


标签: linux bash