Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

string - Bash colon operator in variable substitution?

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.

question from:https://stackoverflow.com/questions/15143863/bash-colon-operator-in-variable-substitution

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This takes the variable branch_name, if it is defined. If it is not defined, use HEAD instead.

See Shell Parameter Expansion for details:

3.5.3 Shell Parameter Expansion

The ‘$’ character introduces parameter expansion, command substitution, or arithmetic expansion. ... The basic form of parameter expansion is ${parameter}.
...
When not performing substring expansion, using the form described below (e.g., ‘:-’), Bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence.

${parameter:-word}

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.


Substrings are covered a few lines below. The difference between the two is

${parameter:-word}

vs

${parameter:offset}
${parameter:offset:length}

${parameter:offset}
${parameter:offset:length}

This is referred to as Substring Expansion. It expands to up to length characters of the value of parameter starting at the character specified by offset.
...
If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value of parameter. ... Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the ‘:-’ expansion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...