Bash command starting with colon with another colon before an equals signs [duplicate]

£可爱£侵袭症+ 提交于 2019-12-07 02:28:39

问题


I could not find any documentation that would explain the syntax below. What does it do inside a bash script? Is it a test?

: ${foo:=bar}; export foo

回答1:


The : command is the 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.

Also Bourne Shell Builtins:

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

The ${foo:=bar} syntax is a special 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 Reference manual 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.

So the command line in your question:

: ${foo:=bar}; export foo

Is two commands:

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

The first of which expands the variable foo and if it is empty or unset assigns it the value bar.

The second of which then exports the foo variable for sub-shells and other processes.



来源:https://stackoverflow.com/questions/30126047/bash-command-starting-with-colon-with-another-colon-before-an-equals-signs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!