简体   繁体   English

这个 bash 参数扩展语法是什么?

[英]What is this bash parameter expansion syntax?

I've never seen this +x} syntax before and I can't find docs about it.我以前从未见过这个+x}语法,我找不到关于它的文档。 What does it do?它有什么作用?

if [[ -z "${EMPLOYEE_CLUSTER+x}" ]]; then
  export EMPLOYEE_CLUSTER=shared
fi

If the variable EMPLOYEE_CLUSTER is defined (even to an empty string), the expansion expands to x .如果定义了变量EMPLOYEE_CLUSTER (甚至定义为空字符串),则扩展将扩展为x Since x is not an empty string, the [[ test will evaluate to true.由于x不是空字符串,因此[[测试将评估为真。 If the variable is not defined, the expansion expands to nothing, and the test evaluates to false.如果未定义变量,则扩展扩展为空,并且测试评估为假。 Note that the presence of a colon in ${EMPLOYEE_CLUSTER:+x} changes the expansion;请注意, ${EMPLOYEE_CLUSTER:+x}冒号的存在改变了扩展; the variable must be set and non-empty to get the x output.必须设置变量并且非空才能获得x输出。

It is a slightly unusual usage, but it is hard to do better in a test like that where an empty value is permissible but the variable must be set.这是一个稍微不寻常的用法,但在允许空值但必须设置变量的测试中很难做得更好。 The notation is more commonly used to conditionally pass values to a command.该符号更常用于有条件地将值传递给命令。 For example:例如:

mythical-creature ${UNICORN:+"-u"} ${UNICORN}

This will pass the -u option to mythical-creature if $UNICORN is defined and non-empty — as well as the value stored in $UNICORN .如果$UNICORN已定义且非空,这会将-u选项传递给mythical-creature - 以及$UNICORN存储的值。 If $UNICORN is not defined and non-empty, no arguments are passed to the command.如果$UNICORN未定义且非空,则不会向命令传递任何参数。

See Shell parameter expansion in the Bash manual — it is the fourth documented notation in this section.请参阅 Bash 手册中的Shell 参数扩展——这是本节中记录的第四个符号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM