LoginSignup
351
320

More than 5 years have passed since last update.

Bashにおける括弧類の意味

Last updated at Posted at 2014-01-20

Bashのスクリプト内で {} や () や [] などの記号の意味。
詳細はここの記事に出ている。
http://stackoverflow.com/questions/2188199/how-to-use-double-or-single-bracket-parentheses-curly-braces
http://mywiki.wooledge.org/BashFAQ/031

bracket [] の意味

[]はtestコマンドの略式。
if文の引数で使う事が多い。

if [ -e "file.txt" ]; then
  echo "File exists"
fi

[ の直後と ]の直前には必ず半角スペースが必要となる。
例えば

if [-e "file.txt" ]; then
  echo "File exists"
fi

と書くと、[-e: command not found というエラーメッセージが出る。

double bracket [[ ]]

bracket と基本的には同じ。 ただし、こちらはbashのビルトインコマンド

(20150428追記) single bracketもbashの場合ビルトインコマンド。
double bracketの方が後に追加されたもので、bash,zsh,Korn shellでのみ使える。
tcshなどでは、[[は使えません。

if [[ -e "file.txt" ]]; then
  echo "File exists"
fi

double bracketの方がsingle bracketよりも機能が充実しており、&&, ||, Pattern matching, 正規表現などが使える。

[[ 1 -lt 2 && 2 -lt 3 ]]
[[ abc == a* ]]
[[ a2 =~ a[0-9] ]]

Parentheses ()

subshellを起動してコマンドを実行する。

(cd /tmp; pwd)  # => "/tmp"
pwd             # => current directory

()の中で実行したコマンドは別プロセスで実行されるので、起動したスクリプト内には何も影響を与えない。
以下のようにサブシェルの実行結果をリダイレクトすることも可能

(cd /tmp; pwd) > pwd.txt

Braces {}

「変数の展開」と 「一連のコマンドをカレントシェルで実行する」の2種類の意味がある。

  1. 変数の展開の例。このように変数名がどこまでなのか明示的に指定する。

    VAR=1234
    echo $VAR       # => "1234"
    echo $VAR1234   # => ""
    echo ${VAR}1234 # => "12341234"
    
  2. 一連のコマンドをまとめて実行。

    { time -p { sleep 1; sleep 2; echo "finished"; } > f.txt; } 2> time.txt
    

この例では f.txt に "finished"という文字列が書き込まれ、timeの実行結果がtime.txtに書き込まれる。
timeコマンドは { sleep ... } の一連の処理の合計時間が書き込まれる。

注意点

  • { ... } の中のコマンドは必ずセミコロンで終端する必要があることに注意。無いとsyntax errorになる。
    • (Parenthesesを使ってサブシェルで実行する場合にはセミコロンは不要)
  • { } は両端に空白が必要。無いとsyntax errorになる。
    • (Parenthesesの場合は不要)
351
320
3

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
351
320