bash 花括号中的变量扩展

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14152534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:09:21  来源:igfitidea点击:

variable expansion in curly braces

bash

提问by user1929290

This is code

这是代码

a=''
b=john
c=${a-$b}
echo $c

And the output is empty line

并且输出是空行

And for similar code where first variable is not initialized

对于第一个变量未初始化的类似代码

b1=doe
c1=${a1-$b1}
echo $c1

And the output is

输出是

doe

I do not understand how bash deals with expanding of variables leading to different results.

我不明白 bash 如何处理导致不同结果的变量扩展。

回答by Jonathan Leffler

There are two variants of the ${var-value}notation, one without a colon, as shown, and one with a colon: ${var:-value}.

${var-value}符号有两种变体,一种没有冒号,如图所示,另一种带有冒号:${var:-value}.

The first version, without colon, means 'if $varis set to any value (including an empty string), use it; otherwise, use valueinstead'.

第一个版本,没有冒号,表示'如果$var被设置为任何值(包括空字符串),使用它;否则,请value改用'。

The second version, with colon, means 'if $varis set to any value except the empty string, use it; otherwise, use valueinstead'.

第二个版本,带冒号,表示'如果$var设置为空字符串以外的任何值,则使用它;否则,请value改用'。

This pattern holds for other variable substitutions too, notably:

这种模式也适用于其他变量替换,特别是:

  • ${var:=value}
    • if $varis set to any non-empty string, leave it unchanged; otherwise, set $varto value.
  • ${var=value}
    • if $varis set to any value (including an empty string), leave it unchanged; otherwise, set $varto value.
  • ${var:?message}
    • if $varis set to any non-empty string, do nothing; otherwise, complain using the given message' (where a default message is supplied if messageis itself empty).
  • ${var?message}
    • if $varis set to any value (including an empty string), do nothing; otherwise, complain using the given message'.
  • ${var:=value}
    • 如果$var设置为任何非空字符串,则保持不变;否则,设置$varvalue
  • ${var=value}
    • 如果$var设置为任何值(包括空字符串),则保持不变;否则,设置$varvalue
  • ${var:?message}
    • 如果$var设置为任何非空字符串,则什么都不做;否则,使用给定的消息'(如果message本身为空,则提供默认消息)进行投诉。
  • ${var?message}
    • 如果$var设置为任何值(包括空字符串),则什么都不做;否则,请使用给定的消息进行投诉'。

These notations all apply to any POSIX-compatible shell (Bourne, Korn, Bash, and others). You can find the manual for the bashversion online — in the section Shell Parameter Expansion. Bash also has a number of non-standard notations, many of which are extremely useful but not necessarily shared with other shells.

这些符号都适用于任何兼容 POSIX 的 shell(Bourne、Korn、Bash 等)。您可以bash在线找到该版本的手册- 在Shell Parameter Expansion部分。Bash 还具有许多非标准符号,其中许多非常有用但不一定与其他 shell 共享。