1

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;

0

3 Answers 3

3

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

That technique isn't used often enough, but it's not what was asked for here -- the if is testing the foo return code. $result can easily be non-empty. On the other hand, of course, this might be what OP was trying to ask for in the first place ...
@jthill There's a reason I started with "Assuming" here. The first option only works given that assumption. The second doesn't require it though.
1

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

2 Comments

But the requirement is that I would need the variable that was initially assigned the value "bar" to be the one that conditionally holds the result of foo(). So at the end of your solution I would need to do default=$val.
Then "that other guy" truly has your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.