131
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

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

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

利用例

#!/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
Sign upLogin
131
Help us understand the problem. What are the problem?