foldrr's weblog

旧ブログ http://d.hatena.ne.jp/foldrr/

bash の大カッコ [ (open bracket)

環境

問題

bash スクリプトで出てくる [ は何者か?

解決

/usr/bin/[ にあるプログラム ファイル。
1文字、しかも記号1文字という変わったプログラム ファイル。
そのため、if は以下のどちらの記述もできる。

if [ 1 == 1 ]; then
  echo 1;
fi
if test 1 == 1; then
  echo 1;
fi

] の存在

[ はプログラム ファイルなので、閉じ括弧に見える ] は、実は [ の引数ってことになる。
[ 1 == 1 ] なら引数を4つ(1, ==, 1, ])渡してるってこと。

機能的には test と同じ

[ は機能的には test と同じみたい。
ところがファイルの実態としては別々に存在する。(エイリアスではない)。

$ which [
/usr/bin/[

$ wcich test
/usr/bin/test

試しに Ubuntu 8.04 でも確認したけれど別々の実態になっている。
bash のソースを見てみたら、builtins/test.def にも test は [ と同じっぽい内容がある。

int
test_builtin (list)
  WORD_LIST *list;
{
    char **argv;
    int argc, result;
    WORD_LIST *t = list;

    /* We let Matthew Bradburn and Kevin Braunsdorf's code do the
     actual test command.  So turn the list of args into an array
     of strings, since that is what his code wants. */
    if (!list)
    {
        if (this_command_name[0] == '[' && !this_command_name[1])
            builtin_error ("missing `]'");

        return (EXECUTION_FAILURE);
    }

Red Hat Linux では、エイリアスになっているみたい。