Marty Wallace
Marty Wallace

Reputation: 35734

Bash variable assignment not working expected

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

Upvotes: 0

Views: 3364

Answers (4)

michael501
michael501

Reputation: 1482

also this ugly thing works too :

status='a'
eval $status=1

echo $a 
1

Upvotes: 0

Reinstate Monica Please
Reinstate Monica Please

Reputation: 11593

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"

Upvotes: 0

Digital Trauma
Digital Trauma

Reputation: 15996

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

Upvotes: 4

Matt K
Matt K

Reputation: 13852

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

Upvotes: 1

Related Questions