d_inevitable
d_inevitable

Reputation: 4451

Bash Assign variable from command with default value

If you have:

val="bar"

Is there easier way of doing the following:

# get value from foo
result=`foo boom baz`

# if we have non falsy value from foo, store it in val:

if [ $result ] ; then
  val=$result
fi

#else val remains at "bar"

Basically I am looking for something equivalent to the following C statement:

val=foo() || val;

Upvotes: 1

Views: 271

Answers (3)

glenn jackman
glenn jackman

Reputation: 246774

I would write it slightly differently to be more explicit about the default value:

default=bar
val=$(foo boom baz)
: ${val:="$default"}      # use the : command to allow side effects to occur
echo "val is now: $val"

Testing: with no foo

val is now: bar

Testing: with foo() { echo qux; }

val is now: qux

Upvotes: 1

that other guy
that other guy

Reputation: 123450

You can do:

val="bar"

result=$(foo boom baz)
val=${result:-$val}       # Assign result if not empty, otherwise val
                          # similar to C  val = *result ? result : val;

echo "val is now $val"

Upvotes: 3

Etan Reisner
Etan Reisner

Reputation: 80931

Assuming the return code from foo is a valid indication of whether it will have output something to fill result you can use:

if result=`foo boom baz`; then
  val=$result
fi

You could also just combine the two original lines (though I don't recommend this):

if result=`foo boom baz`; [ $result ] ; then
  val=$result
fi

Upvotes: 1

Related Questions