1

My curent script

checkargv='^[0-9]+$'
if ! [[ $1 =~ $checkargv ]]
        then
        echo "[!] How many times? $0 [number]" >&2
        exit 1
fi

for (( i=1;i<=$1;i++ ))
do
        x=$[($RANDOM % 100) + 1]
        ./script.sh $x
done

my argv $1 accept right now any number from 0 to does't matter, how can I make the argv accept numbers only from 0 to 100

John Doe
  • 71
  • 3
  • 11
  • `[[ ! "$1" =~ ^[0-9]+$ ]] || [[ "$1" -lt 1 ]] || [[ "$1" -gt 100 ]] && { echo invalid ; exit 1; }` – steve Aug 02 '18 at 17:58

2 Answers2

2
if [ "$1" -lt 1 ] || [ "$1" -gt 100 ]; then
    echo 'error (out of range)' >&2
    exit 1
fi

This assumes that the thing in $1 is actually an integer. You may verify this beforehand with

case "$1" in
    ("" | *[!0-9]*)
        echo 'error (not a positive decimal integer number)' >&2
        exit 1
esac

This will trigger the exit if $1 contains anything other than decimal digits or is empty.

Combining these:

case "$1" in
    ("" | *[!0-9]*)
        echo 'error (not a positive decimal integer number)' >&2
        exit 1
        ;;
    *)
        if [ "$1" -lt 1 ] || [ "$1" -gt 100 ]; then
            echo 'error (out of range)' >&2
            exit 1
        fi
esac

But doing one after the other may look nicer:

case "$1" in
    ("" | *[!0-9]*)
        echo 'error (not a positive decimal integer number)' >&2
        exit 1
esac

if [ "$1" -lt 1 ] || [ "$1" -gt 100 ]; then
    echo 'error (out of range)' >&2
    exit 1
fi

Beware that [ arithmetic operators always consider numbers as decimal even if they start with 0, while the shell's arithmetic expansions in POSIX shells would consider numbers starting with 0 as octal (0100 is 100 for [, but 64 for $((...))).

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
Kusalananda
  • 320,670
  • 36
  • 633
  • 936
0

Use arithmetic instead of regex:

if ! (( num >= 0 && num <= 100 ))

(This assumes num is numeric. If you also need to check to make sure $num is numeric, then use the regex as well.)

L. Scott Johnson
  • 1,462
  • 1
  • 7
  • 16