2

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?

marmistrz
  • 5,974
  • 10
  • 42
  • 94
  • 1
    Aside: The `function` keyword is a bashism that adds no significant value over the POSIX-defined function definition syntax; consider just using `is_number() {`, which will work with all POSIX-compliant shells. – Charles Duffy May 24 '16 at 20:11
  • ...btw, sorta-related (to the code shown as an example of contents, and including some POSIX-compliant answers): http://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash – Charles Duffy May 24 '16 at 20:15

1 Answers1

6

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.

janos
  • 120,954
  • 29
  • 226
  • 236