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.

6
  • No, it doesnt work for negative numbers Commented Mar 24, 2014 at 12:57
  • In that question you can find some answers that take into account negative numbers. Commented Mar 24, 2014 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. Commented Mar 24, 2014 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 Commented Mar 24, 2014 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. :) Commented Mar 24, 2014 at 13:40

1 Answer 1

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]+)?$
Sign up to request clarification or add additional context in comments.

6 Comments

+1 for what i think you paste here queckly
Thanks alot, but when I have number like this "---7" it says it is not a number.
@Sefi you should have only one minus signe before number. If you want more than one minus signe then replace (-)? with (-)*
Thanks! Working perfectly!
In the decimal form you should replace * with ?, otherwise you'll also match input such as 1.2.3. (As an aside: I assume you used (-)? rather than just -? for readability.)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.