Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

${var:=default} vs ${var:-default} - what is difference? [duplicate]

Tags:

variables

bash

Seems both make absolutely same actions.

Empty $var returns defaultvalue in both cases:

$ var=
$ echo ${var:-defaultvalue}
defaultvalue

$ var=
$ echo ${var:=defaultvalue}
defaultvalue

Not empty $var return it's value in both cases:

$ var=var
$ echo ${var:-defaultvalue}
var

$ var=var
$ echo ${var:=defaultvalue}
var

$var not set at all - returns defaultvalue in both cases:

$ unset var
$ echo ${var:-defaultvalue}
defaultvalue

$ unset var
$ echo ${var:=defaultvalue}
defaultvalue
like image 271
setevoy Avatar asked Jun 25 '14 09:06

setevoy


People also ask

What is the default value of variable in shell script?

In simple words, they do not have any initial value. Method 1: We can set variables with default or initial values in shell scripting during echo command with the help of the assignment operator just after the variable name.

How do you assign a default value to a variable in UNIX?

You can use something called Bash parameter expansion to accomplish this. To get the assigned value, or default if it's missing: FOO="${VARIABLE:-default}" # If variable not set or null, use default. # If VARIABLE was unset or null, it still is after this (no assignment done).


2 Answers

They are similar only that ${var:=defaultvalue} assigns value to var as well and not just expand as like it.

Example:

> A='' > echo "${A:=2}" 2 > echo "$A" 2 > A='' > echo "${A:-2}" 2 > echo "$A" (empty) 
like image 57
konsolebox Avatar answered Oct 13 '22 09:10

konsolebox


Positional or special parameters cannot be assigned using := way. See this example:

args() { v=${1:=one}; echo "$v"; }
args
-bash: $1: cannot assign in this way

And this:

args() { v=${1:-one}; echo "$v"; }
args
one

As per man bash: (emphasis is mine to highlight the difference)

${parameter:-word}
Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

${parameter:=word}
Assign Default Values. 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.

like image 21
anubhava Avatar answered Oct 13 '22 08:10

anubhava