Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

colon

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
like image 781
toliveira Avatar asked May 08 '15 14:05

toliveira


1 Answers

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.

like image 126
Etan Reisner Avatar answered Sep 28 '22 04:09

Etan Reisner