What is the difference between “var=${var:-word}”

2020-02-08 07:57发布

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?

标签: linux bash
4条回答
ゆ 、 Hurt°
2楼-- · 2020-02-08 08:30

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
查看更多
Evening l夕情丶
3楼-- · 2020-02-08 08:40
${var:=word}

equals

var=${var:-word}
查看更多
不美不萌又怎样
4楼-- · 2020-02-08 08:42

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.

查看更多
Luminary・发光体
5楼-- · 2020-02-08 08:42

You sometimes see the assignment expansion with the : command:

# set defaults
: ${foo:=bar} ${baz:=qux}
查看更多
登录 后发表回答