Bash script what is := for?
Asked Answered
P

2

37

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} ]
Puttier answered 30/6, 2009 at 15:19 Comment(0)
K
62

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.

Konstantin answered 30/6, 2009 at 15:21 Comment(2)
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 :)Assiduous
@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.Viosterol
B
2

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.

Biradial answered 30/6, 2009 at 15:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.