Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "var=${var:-word}" and "var=${var:=word}"?

Tags:

linux

bash

I read the bash man page on this, but I do not understand the difference. I tested both of them out and they seem to produce the exact same results.

I want to set a default value of a variable if the value was not set via a command-line parameter.

#!/bin/bash

var="$1"
var=${var:-word}
echo "$var"

The code above echoes word if $1 is null and echoes value of $1 if not null. So does this:

#!/bin/bash

var="$1"
var=${var:=word}
echo "$var"

According to Bash man page,

${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.

Is it that they are the same and the ${parameter:=word} just does more?

like image 370
hax0r_n_code Avatar asked Jul 01 '13 12:07

hax0r_n_code


4 Answers

You cannot see the difference with your examples as you're using var two times, but you can see it with two different variables:

foo=${bar:-something}

echo $foo # something
echo $bar # no assignement to bar, bar is still empty

foo=${bar:=something}

echo $foo # something
echo $bar # something too, as there's an assignement to bar
like image 123
Guillaume Avatar answered Oct 31 '22 10:10

Guillaume


${var:=word}

equals

var=${var:-word}
like image 38
Zang MingJie Avatar answered Oct 31 '22 10:10

Zang MingJie


The difference is between use and assignment. Without the =, the value word is used, but not actually assigned to var.

This is most important in the case of variables that are read only -- that is where you cannot assign to them.

For example, you can never assign to the numbered positional parameters. So if you want your function to handle an optional first parameter with a default, you might use code like:

${1:-default}

You can't use the ${1:=default} version there, since you cannot assign to the positional parameter 1. It's read-only.

like image 8
Telemachus Avatar answered Oct 31 '22 10:10

Telemachus


You sometimes see the assignment expansion with the : command:

# set defaults
: ${foo:=bar} ${baz:=qux}
like image 6
glenn jackman Avatar answered Oct 31 '22 09:10

glenn jackman