Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether input is number or not in bash [duplicate]

Tags:

bash

numbers

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?

like image 290
Srikanth Power Avatar asked Oct 28 '25 14:10

Srikanth Power


2 Answers

-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
like image 169
AdrieanKhisbe Avatar answered Oct 31 '25 05:10

AdrieanKhisbe


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.

like image 29
Jens Avatar answered Oct 31 '25 05:10

Jens