Bash – Returning a value from a bash function

bashshell-script

I have a function which returns 1 if the number is a valid ten digit number:

valNum()
{
    flag=1
    if [[ $1 != [1-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] ]]; then
        echo "Invalid Number"
        flag=0
    fi
    return $flag
}

It is getting called by:

if [[ $(valNum $num) -eq 1 ]]; then
      #do something
fi

The function is working fine if the number is valid but is showing syntax error if input a invalid number.

Best Answer

@choroba's answer is correct, however this example might be clearer:

valNum $num
valNumResult=$? # '$?' is the return value of the previous command
if [[ $valNumResult -eq 1 ]]
then
  : # do something
fi

This example is a little longer (setting $valNumResult then querying that value), but more-explicitly describes what happens: that valNum() returns a value, and that value can be queried and tested.

P.S. Please do yourself a favor and return 0 for true and non-zero for false. That way you can use the return value to indicate "why we failed" in the failure case.

Related Question