Souf
Souf

Reputation: 19

Returning a value in a function witch echoes in bash

I'm trying to create a bash function, but this function must show some messages and return a value. It's an example:

#!/bin/bash

function test() {
        echo "Hello"
        return 0
}

if [ $(test) ]; then
        echo "yes"
else
        echo "no"
fi

But I can't capture the returning value, If I do a echo exit. It's possible? Regards

Upvotes: 0

Views: 192

Answers (1)

glenn jackman
glenn jackman

Reputation: 247162

Sure you can: if branches based on the return status, and assigning the output to a variable does not affect the return status:

if output=$(testFunc); then
  echo "success: $output"
else
  echo "failure: $output"
fi

If you need the return value, you get that from the $? variable:

output=$(foo 0)
rc=$?
if [[ $rc -eq 0 ]]; then        # or `if ((rc == 0))`, an arithmetic comparison
  echo "success: $output $rc"   # $rc will always be 0 here
else
  echo "failure: $output $rc"
fi

Upvotes: 1

Related Questions