1

I came across a bash file which has something like this

MYVAR := SomeVal

I know after reading some tutorials you set values as such

MYVAR = SomeVal

What is the difference between the above two ?

2
  • 1
    You should know that you don't put a spaces around the assignment operator.
    – krowe
    Mar 19, 2015 at 23:08
  • Are you sure it wasn't a Makefile? Mar 20, 2015 at 5:57

1 Answer 1

3

You probably saw a parameter expansion to set a default value.

The difference is whether the variable is unset or it is set with a null value:

  1. when the variable is unset, there's no difference

    $ unset MYVAR; : ${MYVAR:=SomeVal}; echo "$MYVAR"
    SomeVal
    $ unset MYVAR; : ${MYVAR=SomeVal}; echo "$MYVAR"
    SomeVal
    
  2. when the variable has a value, there's no difference

    $ MYVAR="foo"; : ${MYVAR:=SomeVal}; echo "$MYVAR"
    foo
    $ MYVAR="foo"; : ${MYVAR=SomeVal}; echo "$MYVAR"
    foo
    
  3. when the variable has null value:

    $ MYVAR=""; : ${MYVAR:=SomeVal}; echo "$MYVAR"
    SomeVal
    $ MYVAR=""; : ${MYVAR=SomeVal}; echo "$MYVAR"
    # empty line
    

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.