且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 bash 中使用 :-(冒号破折号)

更新时间:2022-10-15 20:48:11

如果 $PUBLIC_INTERFACE 存在且不为空,则返回其值,否则返回 "eth0".

bash 手册页中实际上记录了其中的一些内容::>

${parameter:-word} 使用默认值.如果参数未设置或为空,则替换单词的扩展.否则,替换参数值.

${parameter:=word} 分配默认值.如果参数未设置或为空,则将单词的扩展分配给参数.然后替换参数的值.位置参数和特殊参数不能这样赋值.

${parameter:?word} 如果为空或未设置,则显示错误.如果参数为 null 或未设置,则 word 的扩展(或如果 word 不存在则显示该效果的消息)将写入标准错误,并且如果 shell 不是交互式的,则退出.否则,替换参数值.

${parameter:+word} 使用替代值.如果参数为空或未设置,则不替换任何内容,否则替换单词的扩展.

What is the meaning of this style in bash?

${PUBLIC_INTERFACE:-eth0}

What is the purpose of :-?

If $PUBLIC_INTERFACE exists and isn't null, return its value, otherwise return "eth0".

There are actually a few of these documented in the bash man page:

${parameter:-word} Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

${parameter:=word} 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.

${parameter:?word} Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

${parameter:+word} Use Alternate Value. If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.