![パラメータの範囲を設定できますか? [コピー]](https://linux33.com/image/81062/%E3%83%91%E3%83%A9%E3%83%A1%E3%83%BC%E3%82%BF%E3%81%AE%E7%AF%84%E5%9B%B2%E3%82%92%E8%A8%AD%E5%AE%9A%E3%81%A7%E3%81%8D%E3%81%BE%E3%81%99%E3%81%8B%EF%BC%9F%20%5B%E3%82%B3%E3%83%94%E3%83%BC%5D.png)
私はこのコードを持っています:
if [[ $1 = "-s" ]] && [[ $2 = 0-9 ]]
then
echo "yes"
fi
0-9は私には適していません。私が本当に欲しいのは、-x 3(または任意の数字)のようなものを入力することです。
答え1
if [[ $1 = "-s" ]] && [[ $2 -ge 0 ]] && [[ $2 -le 9 ]]
-ge
:異常
-le
:以下
答え2
可能ですが、文字クラス([0-9]
)を使用する必要があります。たとえば、
if [[ "$1" = "-s" ]] && [[ "$2" = [0-9] ]]
then
echo "yes"
fi
ただし、上記は$2
単一の数字で構成されている場合にのみ適用されます。$2
1 つ以上の数値を含めるには、次を使用します。
if [[ "$1" = "-s" ]] && [[ "$2" != *[!0-9]* && "$2" = [1-9]* ]]
then
echo "yes"
fi
最新のbashバージョンでは正規表現を使用することもできます。
if [[ "$1" = "-s" ]] && [[ "$2" =~ ^[0-9]+$ ]]
then
echo "yes"
fi
文字列の^
始まりと終わりを一致させます。 「0個以上」を$
意味します。これは、文字列に最初から最後まで1つ以上の数字しか含まれていない場合にのみ当てはまります+
。^[0-9]*$
答え3
[ "${#1}${1#-s}" = "$((${2%%*[!0-9]*}0?2:-1))" ] &&
echo yes
...時々比較のバランスをとるとテストが短くなることがあります。
しかし、私は好むcase
:
case ${1#-s}:$2 in
(*:*[!0-9]*|*:) ;;
("${1:+:$2}") echo yes.
esac
基本的にアイデアは除外することです。どの数字ではなく数字と一致します。たとえば、
[ "${2:+1$2}" = "1${2##*[!0-9]*}" ] &&
echo '"$2"' contains at least one character which \
is a digit and zero which are not digits.
case
いくつかのポイントがあるので、これははるかに簡単です。
case $1:$2 in
(*:*?"$2")
echo '"$1"' contains a "':'";;
(*:*[!0-9]*|*:0*[89]*|*:)
echo '"$2"' either contains a not-digit character, no characters, \
or is an invalid octal constant - or perhaps a mix-and-match;;
([!-]*|?[!s]*|??[!:]*)
echo '"$1"' is either empty, doesn\'t match '-s' in its first two characters, \
or is more than two characters. Or perhaps a mix-and-match.;;
(*) echo there are no more possibilities other than the one you want.
echo but you can get here a lot sooner, as demonstrated above.
esac