4

I want to write program to check whether the given input is number or not. Can anyone help me?

 if [ $Number -ne 0 -o $Number -eq 0 2>/dev/null ]
 then ...

and what -o stands for in above command?

0

2 Answers 2

8

-o is the or operator. So your test check if your number is not equal to 0 or if it's equals to 0.

(so it should always return true).

To check if it's a number, you could use a regexp: this should be working:

[[ "$number" =~ ^[0-9]+$ ]]

To see the list of all available flags, you should look at man test


Details:

  • [[ is a extended bash test command. It supports more operator than test/[.
  • =~ compare the first argument again a regular expression
  • ^[0-9]+$ is the regular expression. ^ is an anchor for the start of the string, $ for the end. [0-9] means any char between 0 and 9, and + is for the repetition of the latest pattern
Sign up to request clarification or add additional context in comments.

2 Comments

thank you what u gave is working fine for my programm.I am new to linux can you please explain the above command given by you?
update the question with details :)
3

The POSIX way to do this (for integers; floats are more complicated) is

 case $number in
   (*[^0-9]*) printf '%s\n' "not a number";;
   ()         printf '%s\n' "empty";;
   (*)        printf '%s\n' "a number";;
 esac

This works for any Bourne shell, unlike the [[ ... ]] construct, which is non-portable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.