14
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

シェルスクリプト(bash)の「 [ ] 」と「 [[ ]] 」の違い

Last updated at Posted at 2017-05-02

[]では予期せぬ変数展開でエラーが発生する場合があるので[[ ]]を使う。
※本来は使い分けるべきなのだろうが、現状[[ ]]のみでこと足りている

エラーの例:

if [ `echo "Count aaaa " | grep Count` ] ; then
    echo 'OK'
fi

./test.sh: line 4: [: Count: unary operator expected
if [ `echo "Count aaaa , bbb" | grep Count` ] ; then
    echo 'OK'
fi

./test.sh: line 4: [: 引数が多すぎます

[[ ]]だと問題ない:

if [[ `echo "Count aaaa " | grep Count` ]] ; then
    echo 'OK'
fi

OK
if [[ `echo "Count aaaa , bbb" | grep Count` ]] ; then
    echo 'OK'
fi

OK

[]でも問題ない場合もある

if [ `echo "Count" | grep Count` ] ; then
    echo 'OK'
fi

OK

以下のコードでファイルの中身によってエラーが出たり出なかったりで地味にハマりました。

cat test.txt | while read LINE;do
  if [ `echo $LINE | grep Count` ] ; then
    echo 'OK'
  fi
done

※以下のように正規表現を使う場合、[[ ]]を使うことはよく知られています

if [[ $name =~ hogehoge ]] ; then
  echo match
fi
14
15
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?