Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...