/bin/dash: check whether $1 is a number
The following detect integers, positive or negative, and work under dash
and are POSIX:
Option 1
echo "$1" | grep -Eq '^[+-]?[0-9]+$' && echo "It's an integer"
Option 2
case "${1#[+-]}" in
''|*[!0-9]*)
echo "Not an integer" ;;
*)
echo "Integer" ;;
esac
Or, with a little use of the :
(nop) command:
! case ${1#[+-]} in *[!0-9]*) :;; ?*) ! :;; esac && echo Integer
Whether dash
, bash
, ksh
, zsh
, POSIX sh
, or posh
("a reimplementation of the Bourne shell" sh
) ; the case
construct is the most widely available and reliable:
case $1 in (*[!0-9]*|"") false ;; (*) true ;; esac