Answers for "bash check if variable is a number"

3

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
Posted by: Guest on May-02-2020
0

check if variable is a number in bash

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

Code answers related to "bash check if variable is a number"

Code answers related to "Shell/Bash"

Browse Popular Code Answers by Language