Do these two code snippets, one using the colon equal notation, and the other using the double bracket program exhibit the same behavior?
: "${foo:=bar}"
and
if ! [[ $foo ]]; then
foo=bar
fi
If they are the same in behavior, then which one is preferred stylistically? I've seen both of these used in various places and I can't decide which one is better for maintainability and readability.
As far as I'm aware, they're functionally equivalent. As for which is best, I'd say that's a matter of taste. Personally I'd prefer : ${foo:=bar}
as it's more concise but others less familiar with the syntax would probably go for the more obvious approach.
Note that your first approach uses standard shell features, so should work on any POSIX-compliant shell. To make your second approach more portable, I'd go with:
if [ -z "$foo" ]; then
foo=bar
fi
As suggested in the comments, another option which could be seen as a compromise between clarity and brevity would be:
foo=${foo:-bar}
${foo:-bar}
evaluates to $foo
if it's already set, else bar
.