marmistrz
marmistrz

Reputation: 6414

Bash - return a boolean check

I created a simple function which does a regex check:

function is_number()
{
    return [[ "$1" =~ ^-?[0-9]+$ ]]
}

What I get is

return: [[: numeric argument required

What am I doing wrong?

Upvotes: 2

Views: 1759

Answers (1)

janos
janos

Reputation: 124824

You don't need the return statement. The return value of the function is the exit code of the last statement. So this is enough:

function is_number()
{
    [[ "$1" =~ ^-?[0-9]+$ ]]
}

The equivalent of this using an explicit return statement would be:

function is_number()
{
    [[ "$1" =~ ^-?[0-9]+$ ]]
    return $?
}

But don't do this, it's pointless.

Upvotes: 6

Related Questions