Bash > 文字列の比較

更新日 2014-11-04
広告

文字列を比較する方法を紹介します。

基本的な比較

文字列は、if文を使って比較できます。if文で利用するオプションを表にまとめます。

オプション 比較の内容
= 文字列同士が等しいか
!= 文字列同士が異なるか
-n 文字列の長さが1以上か
-z 文字列の長さが0か

以下に、サンプル test-string.sh を示します。

#!/bin/bash
 
foo=aaa
var=aaa
 
if [ ${foo} = ${var} ]; then
    echo "equal"
fi

if [ ${foo} != "bbb" ]; then
    echo "not equal"
fi
 
if [ -n ${foo} ]; then # 変数fooのサイズが1以上であれば真
    echo "not null"
fi
 
foo=
if [ -z ${foo} ]; then # 変数fooのサイズが0であれば真
    echo "null"
fi
これを実行すると、以下の結果になります。
$ ./test-string.sh 
equal
not equal
not null
null

文字が含まれていることを判定

文字列の中に、特定の文字が含まれているかどうか判定する方法を紹介します。 以下に例を示します。
#!/bin/bash

text="hoge"

if [ $(echo $text | grep -e 'h') ]; then
    echo "hoge include h"
else
    echo "hoge doesn't include h"
fi

if [ $(echo $text | grep -e 'a') ]; then
    echo "hoge include a"
else
    echo "hoge doesn't include a"
fi
以下が実行結果です。
$ bash /tmp/hoge.sh
hoge include h
hoge doesn't include a
広告
お問い合わせは sweng.tips@gmail.com まで。
inserted by FC2 system