0
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

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

0=1 makes perfect sense syntactically, but it will not do what the user intended. If an executable file named 0=1 exists in the user's path, it will be run.
@chepner - yes, very true.
1

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

1 Comment

Not quite that hairy; parsing is done first, but [ is not syntax (it's a command name), so it works as expected. foo=if; $foo [ -f .bashrc ]; then echo "hey"; fi would properly fail with a syntax error.
0

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"

Comments

0

also this ugly thing works too :

status='a'
eval $status=1

echo $a 
1

1 Comment

Or you can achieve extra levels of indirection using a parameter expansion like this: a=1; status='a'; echo ${!status}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.