I inherited some bash code and these two lines are bewildering me:
branch_name=`git describe --contains --all HEAD`
branch_name=${branch_name:-HEAD}
My understanding of the :
colon operator is that is creates a substring based on an index so using a string, -HEAD
in this case, does not make any sense.
This takes the variable
branch_name
, if it is defined. If it is not defined, useHEAD
instead.See Shell Parameter Expansion for details.
Substrings are covered a few lines below. The difference between the two is
vs
In this case, the colon is just a modifier for the
-
operator.${branch-HEAD}
would expand to "HEAD" only ifbranch
is unset, while${branch:-HEAD}
expands to "HEAD" ifbranch
is the null string as well.In bash,
${VAR1:-VAR2}
is equivalent to SQL'scoalesce(VAR1, VAR2)
, or C#'sVAR1 ?? VAR2
.In your case:
The first line executes the
git
command and sets the value in thebranch_name
variable, then, the second line coalesces its value assigning the value ofHEAD
ifbranch_name
is null.As you said
${VAR1:NUM}
is a string prefix operation (left
in SQL), which when used with a negative number, as${VAR1: -NUMBER}
becomes a suffix (right
) operation. Note the whitespace before the minus sign: if you skip that whitespace it becomes thecoalesce
operation as I've said before.