tags:

views:

195

answers:

3

Does anyone know what is := for?

I tried googling but it seems google filters all symbol?

I know the below is something like checking if the variable HOME is a directory and then something is not equal to empty string.

  if [ "${HOME:=}" != "" ] && [ -d ${HOME} ]
+6  A: 

From Bash Reference Manual:

${parameter:=word}

If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.

Basically it will assign the value of word to parameter if and only if parameter is unset or null.

Andrew Hare
Beat me by one second :)
Jon Skeet
And me by two ;)
bedwyr
I've seen := a lot of places. Ussually I read it is "defined by". In C++, C#, Java (+ a hundred other places) := equals =. And when this is true, ussually = equals ==. Wow - that was a subtle point by me. Sorry for being so bad at explaining myself :)
cwap
@Meeh: As far as I know, this is the only situation where bash uses ":=". For assignment, "=" is used and for equality comparison, either "=" or "==" can be used. Bash also accepts assignment operators like "+=". I'm not sure which operator you're saying C++, etc., use, but it's "=". Languages like Pascal and Ada use ":=" and so might be considered to be rarer.
Dennis Williamson
+1  A: 

From the Bash man page:

Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.

Man pages are a wonderful thing. man bash will tell you almost everything you want to know about Bash.

mipadi
A: 

Here "${HOME:=}" is a more or less a no-op, since it returns $HOME if it's set and nothing if it's not.

if [ "${HOME:=}" != "" ] && [ -d ${HOME} ]

This would function identically:

if [ "${HOME}" != "" ] && [ -d ${HOME} ]

If you had something after the equal sign, the first part of the if would always be true.

if [ "${HOME:=here}" != "" ] && [ -d ${HOME} ]

whatever happened you'd always get a string that's not equal to "".

However, this would depend on whether $HOME and $DEFAULT were both null:

if [ "${HOME:=$DEFAULT}" != "" ] && [ -d ${HOME} ]
Dennis Williamson
It's not quite a no-op, since if $HOME is undefined, it will be set to the empty string.
camh
@camh: In bash, there is virtually no difference between an undefined variable and one with a null value.
Dennis Williamson