Ryan Schubert
Ryan Schubert

Reputation: 186

setting default variables with parameter expansion vs if/else test -z

So traditionally when I write bash scripts with argument flags I implement default values with a basic test statement like so

if [ -z $foo ]
then
    foo=$bar
fi

Today I came across more advanced parameter expansions that seem to do the same thing

${foo:=$bar}

How do these two methods compare? What are their advantages/disadvantages?

edit: fixed some typos pointed out in the comments

Upvotes: 3

Views: 498

Answers (1)

chepner
chepner

Reputation: 531808

The typical idiom is

: ${foo:=$bar}

as a replacement for

if [ -z "$foo" ]
then
    foo=$bar
fi

(note the quotes and whitespace!)

In the former, the parameter expansion handles the assignment for an otherwise do-nothing command. It's more concise, but otherwise there's little reason for choosing one over the other. Note that both are supported by POSIX.

Upvotes: 5

Related Questions