I've seen : "${DB_HOST:=localhost}" because it assigns the variable if not set (: $… is just to run assignments standalone).

But that has the same effect like DB_HOST="${DB_HOST:-localhost} (use the string if not set), which is more readable.

While something like echo "${DB_HOST:=localhost}" smells from a mile, because it has output with side-effects.

all 7 comments

sorted by: hot top controversial new old
[–] 7 points 1 week ago (2 children)

The argument for : "${foo:=x}" is usually that you don't have to repeat foo, leading to less opportunity for errors and generally DRY.

  • source
  • hideshow 2 child comments
  • [–] 2 points 1 week ago

    I'd you're concerned about this, it's up to you to change your bash script style.

    Use "set -euo pipefail" and don't use ": =". You can't stop others from doing so though. It's their code, their choice.

    I never use ": =" in bash though.

  • source
  • [–] 2 points 1 week ago* (last edited 1 week ago) (2 children)

    But that has the same effect like DB_HOST="${DB_HOST:-localhost} (use the string if not set), which is more readable.

    I disagree that the duplicate reference would be more readable. Instead, the reader needs (if they care about the meaning of the code) to double-check whether the two duplicate names are exactly the same, or whether they are subtly different. At which point the reader needs to wonder why the code isn't written using the form without the repeated name. So, that's not a readability improvement.

    Related to that: Code with duplicate references in a single expression or statement leaves open the likelihood that one or more of them will contain a typo or an easily-overlooked difference, leading to bugs. DRY is a good principle to avoid that.

  • source
  • hideshow 2 child comments
  • [–] [S] 1 point 1 week ago (1 child)

    I think it makes it easier to read, because the other variable assignments are also this way. DRY is from a time where one-letter variables were common.

  • source
  • parent
  • hideshow 1 child comment