Reputation: 4451
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
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
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
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