Kan Li
Kan Li

Reputation: 8807

Assign command output to a variable and do if branch on the return value

I want to do the following thing

X=$(some_command)
if [ $? == 0 ]; then
  do_something
  echo $x
else
  do_something_else
fi

Basically, I want to execute some command, store the output to some variable. Meanwhile, I want to branch based on whether the command succeeded or not. The above way works, but looks ugly. Is it a smarter way?

Thanks.

Upvotes: 0

Views: 735

Answers (1)

Barmar
Barmar

Reputation: 782785

if x=$(some command); then
  do_something
  echo $x
else
  do_something_else
fi

The if command works by running the command and testing whether it was successful, and executing the then or else branch depending on it.

Upvotes: 6

Related Questions