view counter

Unix Bash script - Check if integer or not

Thanks to Jadu Saikia for this story

Please find below two UNIX bash scripts to test if the entered input is integer or not. Request all to suggest if any other alternatives to check this. Thanks in advance.1) Script 1:$ cat check-integer.sh#!/bin/sh#Check if input is integer or not[ -z $1 ] && echo "No input, exiting .." && exit[[ $1 = *[![:digit:]]* ]] && echo "Not Integer" || echo "Integer"Executing/testing it:$ ./check-integer.sh No input, exiting ..$ ./check-integer.sh 12Integer$ ./check-integer.sh 12.1Not Integer$ ./check-integer.sh testvarNot Integer2) Script 2:#!/bin/sh#Check if input is integer or not[ -z $1 ] && echo "No input, exiting .." && exitresult=$(echo $1 | egrep ^[[:digit:]]+$)if [ "$result" = "" ] ; then echo "Not Integer"else echo "Integer"fiExecuting/testing it:$ ./check-integer.sh No input, exiting ..$ ./check-integer.sh 12Integer$ ./check-integer.sh 12.1Not Integer$ ./check-integer.sh testvarNot Integer$ ./check-integer.sh 12U Not Integer$ ./check-integer.sh U12Not IntegerThe if else in the second script can also be written using && and ||, something like:[ "$result" = "" ] && echo "Not Integer" || echo "Integer"Related posts:- Use of $() as an alternative to backtick evaluation in bash - UNIX Bash function to compare equality of multiple numbers

view counter

Read the entire article at its source

view counter