Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the result of ${VAR:=value} in a bash script

Tags:

bash

shell

I'm looking at several bash scripts that use := in between ${ }. For example, the pattern looks like this:

export VAR=${VAR:=value}

What is this doing? Is it assigning value to VAR if VAR does not exist?

like image 665
whyceewhite Avatar asked Apr 03 '14 16:04

whyceewhite


People also ask

What is ${ in shell script?

Here are all the ways in which variables are substituted in Shell: ${variable} This command substitutes the value of the variable. ${variable:-word} If a variable is null or if it is not set, word is substituted for variable.

What does ${ var mean?

In the bash shell, ${! var} is a variable indirection. It expands to the value of the variable whose name is kept in $var . The variable expansion ${var+value} is a POSIX expansion that expands to value if the variable var is set (no matter if its value is empty or not).

What does ${ 1 mean in bash script?

- 1 means the first parameter passed to the function ( $1 or ${1} ) - # means the index of $1 , which, since $1 is an associative array, makes # the keys of $1.

What is ${ 0 in bash?

${0} is the first argument of the script, i.e. the script name or path.


2 Answers

As per documentation:

${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 it exports the VAR value with its value, or if it is unset/null it is exported with literal value.

like image 195
Caramiriel Avatar answered Oct 05 '22 12:10

Caramiriel


From the man page:

   ${parameter:=word}
          Assign Default Values.  If  parameter  is  unset  or  null,  the
          expansion of word is assigned to parameter.  The value of param‐
          eter is then substituted.   Positional  parameters  and  special
          parameters may not be assigned to in this way.

In other words, it basically lets you specify a default value for a variable. If the variable is unset/null, then it will be set to that value and the value will be used as the expansion as well.

like image 23
FatalError Avatar answered Oct 05 '22 11:10

FatalError