argvが0から100までの数値であるBASHを確認する

argvが0から100までの数値であるBASHを確認する

私の現在のスクリプト

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

私のargv $ 1は0から0から100までの数字を受け入れます。気にしません。 argvに0から100までの数字のみを許可させるにはどうすればよいですか?

ベストアンサー1

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

これは in の内容が$1実際に整数であると仮定します。事前に確認できます。

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

exit$110 進数以外の数値が含まれているか空白の場合に実行されます。

総合してみると:

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

しかし、順番に実行する方が良く見えるかもしれません。

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

算術演算子は、64で[始まっても数字を常に素数として扱います0[$((...))

おすすめ記事