変数内の文字列の大文字と小文字を変更するにはどうすればよいですか?

変数内の文字列の大文字と小文字を変更するにはどうすればよいですか?
"Enter test: "
read test

if [[ $test == "a" ]]; then
    echo "worked"
else
    echo "failed"
fi

これは私が行っているテストの簡単な説明ですが、「A」と入力すると失敗します。変数の段階ですべてを小文字に変更してテストが一致するようにすることはできますか?

答え1

標準のsh(POSIX および Bourne) 構文を使用します。

case $answer in
  a|A) echo OK;;
  *)   echo >&2 KO;;
esac

または:

case $answer in
  [aA]) echo OK;;
  *)    echo >&2 KO;;
esac

bashkshまたはzsh(非標準[[...]]構文をサポートする3つのシェル)を使用すると、小文字変数:

typeset -l test
printf 'Enter test: '
read test
if [ "$test" = a ]; then...

(bash一部のロケールでは大文字小文字の変換が正しく行われないことに注意してください)。

答え2

これを実現するには、いくつかの便利な方法があります ( bash)。

2つの小切手

echo -n "Enter test: "
read test

if [[ $test == "a" || $test == "A" ]]; then
    echo "worked"
else
    echo "failed"
fi

入力を小文字にする

echo -n "Enter test: "
read test
test="${test,,}"

if [[ $test == "a" ]]; then
    echo "worked"
else
    echo "failed"
fi

両方の場合の正規表現

echo -n "Enter test: "
read test

if [[ $test =~ ^[aA]$ ]]; then
    echo "worked"
else
    echo "failed"
fi

シェルに大文字と小文字を無視させる

echo -n "Enter test: "
read test

shopt -s nocasematch
if [[ $test == a ]]; then
    echo "worked"
else
    echo "failed"
fi

答え3

これを行うにはいくつかの方法があります。bash の最新バージョンを使用している場合は、非常に簡単です。の大文字と小文字を変換するtestか、大文字と小文字の両方の a に一致する正規表現を使用できます。

まず正規表現の方法:

read -p "enter test: " test;[[ $test =~ ^[Aa]$ ]] && echo yes || echo no

次にケースシフターです:

read -p "enter test: " test;[[ ${test^^} = A ]] && echo yes || echo no

答え4

sed -ne '/^[aA]$/!i\' -e failed -e 's//worked/p;q' </dev/tty

関連情報