I am trying to use case to run this function
if [[ $input -gt 0 || $input -eq 0 ]]; Is it possible to put in case to test the input for greater than 0 or equal to 0, or even 0 and less than 0, in case.
This sample sh script validates that a variable is an integer.
#!/bin/sh num=$1 if [ $num -eq $num ] 2> /dev/null then case 1 in $(($num < 0)) ) echo $num is negative.;; $(($num <= 100)) ) echo $num is between 0 and 100.;; $(($num <= 1000)) ) echo $num is between 100 and 1000.;; * ) echo $num is greater than 1000.;; esac else echo $num is not a number. fi We verify the variable is a number by using the -eq operator. We need to suppress its output to stderr in case it's not a number.
If the variable contains an integer, the case will then evaluate ranges in the laid out form. The expressions $(( some comparison )) will either evaluate to "true" (1) or "false" (0); this way, you can test any given list of ranges.
expr when you don’t need to? Why are you using a constant word and a variable pattern in your case statement. This seems unnecessarily complicated and convoluted. SC2004 (style): $/${} is unnecessary on arithmetic variables. May lead to "subtle bugs": shellcheck.net/wiki/SC2004 If only integers need to be handled and -0 is not need to be handled correctly, the following works:
case "$input" in ''|*[!0-9-]*|[0-9-]*-*) echo "invalid input" ;; [0-9]*) echo "input >= 0" ;; -[1-9]*) echo "input < 0" ;; *) echo "invalid input" ;; esac But it is usually better to use if .. then .. elif ... then .. else .. fi constructs for distinction of cases with more complicated expressions than case with pattern matching.
123asd, -1aa. 123ad. [ num -gt -1 ]? [ "$input" -gt -1 ] || exit ...or...
case ${input:?NULL} in (?*[!0-9]*|[!-0-9]*|[!0-9]) ! : ;; (-*[!0]*) echo \<0 ;; (*[!0]*) echo \>1 ;; (0*) echo 0 ;; esac (*) matching zero then have you tested this? The first var expansion exits the shell for a null value. The next in line matches any char which is not 0-9, the next any which is not 0 - 1 or more 0 characters is the only possibility there. bash. case $([[ $input =~ ^-?[0-9]+$ ]] && [[ $input -gt 0 || $input -eq 0 ]] ; echo $?) in 0) echo "good" ;; 1) echo "bad" ;; *) echo "weird" ;; esac If you do not like the complexity inside the case, at least the regex matching works well and simple.
if [ "$a" -ge "$b" ]means "greater than or equal to". So you can just doif [[ "${input}" -ge 0 ]];. But beware that Bash treats empty strings and all non-numeric strings as "0" (basically anything that cannot be coerced into a number), which can really bite you if you are truly looking for "0"!