bash script check if var is number code example

Example 1: bash check if variable is a number

# bash check if $1 is an integer

# compact version:
[ -n "$1" ] && echo "\$1 : is EMPTY" && exit 1
[ "$1" -eq "$1" ] 2>/dev/null && echo "$1 : is a number" || echo "$1 : not a number"

# long version
if [ "$1" -eq "$1" ] 2>/dev/null; then
	echo "$1 : is a number"
else
	[ -n "$1" ] && echo "$1 : is EMPTY" && exit 1
	echo "$1 : not a number"
fi

Example 2: check if variable is a number in bash

re='^[0-9]+$'
if ! [[ $yournumber =~ $re ]] ; then
   echo "error: Not a number" >&2; exit 1
fi