e-info128
e-info128

Reputation: 4072

How to set variable value with conditional in one line?

Have this:

DATABASE_HOST=[ $# -le 3 ] && $3 || '127.0.0.1';

But does not works. Is a bash script with 3 optional parameters:

db.sh user dbname hostname

I want to replace my old method:

if [ $# -le 3 ]
then
    DATABASE_HOST=$3;
else
    DATABASE_HOST='127.0.0.1';
fi

Upvotes: 5

Views: 3482

Answers (1)

anubhava
anubhava

Reputation: 785481

You can shorten it with this BASH construct:

DATABASE_HOST="${3:-127.0.0.1}"

As per man bash:

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

Upvotes: 9

Related Questions