Bash 命令以冒号开头,在等号之前有另一个冒号

Bash command starting with colon with another colon before an equals signs

我找不到任何可以解释以下语法的文档。 它在 bash 脚本中做了什么?是测试吗?

: ${foo:=bar}; export foo

:命令是null utility:

This utility shall only expand command arguments. It is used when a command is needed, as in the then condition of an if command, but nothing is to be done by the command.

还有Bourne Shell Builtins:

Do nothing beyond expanding arguments and performing redirections. The return status is zero.

${foo:=bar} 语法是一种特殊的 Parameter Expansion:

${parameter:=[word]}

Assign Default Values. If parameter is unset or null, the expansion of word (or an empty string if word is omitted) shall be assigned to parameter. In all cases, the final value of parameter shall be substituted. Only variables, not positional parameters or special parameters, can be assigned in this way.

Bash参考手册entry:

${parameter:=word}

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.

所以你问题中的命令行:

: ${foo:=bar}; export foo

是两条命令:

  1. : ${foo:=bar}
  2. export foo

其中第一个扩展变量 foo,如果它为空或未设置,则为其分配值 bar

第二个然后导出子 shell 和其他进程的 foo 变量。