0

In python I can write this piece of code:

if (result := some_function()) > 0:
    # do some thing with result

Is it possible in Bash script?

2 Answers 2

1

Yes, but preferably not in a single statement.

if foo=$(bar); [[ $foo == 42 ]]; then

which isn't too different from:

foo=$(bar); if [[ $foo == 42 ]]; then

You can put literally anything in the if condition, including a whole another if block or a case or whatever else as long as it's valid Bash code. The status of the last command is the one that will be checked as the condition.

If you really want a single statement, then the "assign default" expansion can be abused for this, if the variable is not yet set to anything – but please don't do this in scripts that other people will have to read. (Nor the Python example, for that matter. Just because you can write a certain piece of code, doesn't mean you should.)

if [[ ${foo:=$(bar)} == 42 ]]; then
2
  • From the last piece of code in your answer, I go for if [ ! -z "${result=$(some_function)}" ] and it solves my problem. Thanks.
    – nt.dinh
    Commented May 1 at 10:35
  • I regret answering this question. Commented May 1 at 10:36
0

It's a useful technique to capture the output and also to act on the command's exit status:

if result=$(some command); then
    echo "'some command' succeeded and produced the following output:"
    echo "$result"
else
    echo "'some command' failed and produced the following output:"
    echo "$result"
fi

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .