What is the difference between “var=${var:-word}” and “var=${var:=word}”?

后端 未结 4 1669
北恋
北恋 2020-12-14 03:10

I read the bash man page on this, but I do not understand the difference. I tested both of them out and they seem to produce the exact same results.

I want to set a

相关标签:
4条回答
  • 2020-12-14 03:26

    You sometimes see the assignment expansion with the : command:

    # set defaults
    : ${foo:=bar} ${baz:=qux}
    
    0 讨论(0)
  • 2020-12-14 03:30

    You cannot see the difference with your examples as you're using var two times, but you can see it with two different variables:

    foo=${bar:-something}
    
    echo $foo # something
    echo $bar # no assignement to bar, bar is still empty
    
    foo=${bar:=something}
    
    echo $foo # something
    echo $bar # something too, as there's an assignement to bar
    
    0 讨论(0)
  • 2020-12-14 03:33
    ${var:=word}
    

    equals

    var=${var:-word}
    
    0 讨论(0)
  • 2020-12-14 03:52

    The difference is between use and assignment. Without the =, the value word is used, but not actually assigned to var.

    This is most important in the case of variables that are read only -- that is where you cannot assign to them.

    For example, you can never assign to the numbered positional parameters. So if you want your function to handle an optional first parameter with a default, you might use code like:

    ${1:-default}
    

    You can't use the ${1:=default} version there, since you cannot assign to the positional parameter 1. It's read-only.

    0 讨论(0)
提交回复
热议问题