Help us understand the problem. What is going on with this article?

Bashで変数を大文字小文字変換(uppercase/lowercase)する

More than 1 year has passed since last update.

bashのバージョン4以降から使えるようになった構文なんだけど、大文字小文字無視した文字列で比較したい時とかに地味に便利なのでメモ。

記述 説明
${v^} 大文字化(1文字目のみ) v="ho ge"; echo ${v^}→Ho ge
${v^^} 大文字化(全文字) v="ho ge"; echo ${v^^}→HO GE
${v,} 小文字化(1文字目のみ) v="HO GE"; echo ${v,}→hO GE
${v,,} 小文字化(全文字) v="HO GE"; echo ${v,,}→ho ge
${v~} 大小反転(1文字目のみ※) v="ho GE"; echo ${v~}→Ho gE
${v~~} 大小反転(全文字) v="ho GE"; echo ${v~~}→HO GE

※何故か、大小反転だけは空白を含む文字列に対して、空白毎にその後の1文字を変換するという変な動作になる。大文字化と小文字化に関しては空白があっても特別なことは起こらない。

利用例

#!/bin/bash
echo -n "押すなよ!絶対押すなよ! [y/N]"
read confirm
if [[ ${confirm,,} = y ]]; then
  echo "素直か!"
else
  echo "どーん!"
fi

bashが古い場合は…

trでも使っとけばいいんじゃね。

$ tr '[a-z]' '[A-Z]' <<<hoge
HOGE
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away