1

I want to check if a certain string is a number, I tried this way:

if ${string} == *[!0-9]*
else echo its a number

but when I have a negative number, it says it's not a number, and i want it to work for negative numbers too.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Michael
  • 427
  • 1
  • 3
  • 13
  • No, it doesnt work for negative numbers – Michael Mar 24 '14 at 12:57
  • In that question you can find some answers that take into account negative numbers. – fedorqui Mar 24 '14 at 12:57
  • @Sefi, the accepted answer there had a solution for negative numbers in its comments; I've edited it into the answer proper. – Charles Duffy Mar 24 '14 at 13:18
  • @CharlesDuffy Thanks a lot, but when I have a number like this "---7" it says it is not a number instead of reading it as -7 – Michael Mar 24 '14 at 13:38
  • @Sefi, `---7` *isn't* a number; the logic is correct. If you wanted zero-or-more `-` signs, though, you'd use `-*` instead of `-?`. By the way, the comments in the other answer discuss this too. :) – Charles Duffy Mar 24 '14 at 13:40
  • @Sefi, ...or rather, `---7` is only as much a number as `1+2` is a number; it's a unary operation being applied to the number `-7` twice, flipping it each time, just as `1+2` is a binary operation being applied to two numbers. – Charles Duffy Mar 24 '14 at 13:42

1 Answers1

3

Try this script

#!/bin/bash

string=$1

if [[ "$string" =~ ^(-)?[0-9]+$ ]]; then
  echo 'Number'
else
  echo 'Not number'
fi

This works only for integers.

If you want to match and decimal number then use this test

"$string" =~ ^-?[0-9]+(\.[0-9]+)?$
djm.im
  • 3,295
  • 4
  • 30
  • 45