2017-01-11 11 views
2

私はグループへの必要性を持っているが、私はそうのようなログファイルを分離するために、それらの出力を指示できるように、私は巻き毛のロギングを容易にするために、ブレースを追加しているが、私のシェルスクリプトで中括弧を...中括弧内からbashシェルスクリプトを終了するには?

>cat how-to-exit-script-from-within-curly-braces.sh 

{ 
    printf "%d\n" 1 
    printf "%d\n" 2 
} | tee a.log 
{ 
    printf "%d\n" 3 
    printf "%d\n" 4 
} | tee b.log 

    >./how-to-exit-script-from-within-curly-braces.sh 
1 
2 
3 
4 
    >cat a.log 
1 
2 
    >cat b.log 
3 
4 
    > 

使用してコマンドexitコマンドが中括弧の中で呼び出されると、スクリプトを終了させたいと思うでしょう。

もちろんそうはありません。これは、中括弧を終了してからスクリプトにそう...

>cat how-to-exit-script-from-within-curly-braces.sh 

{ 
    printf "%d\n" 1 
    exit 
    printf "%d\n" 2 
} | tee a.log 
{ 
    printf "%d\n" 3 
    printf "%d\n" 4 
} | tee b.log 

    >./how-to-exit-script-from-within-curly-braces.sh 
1 
3 
4 
    >cat a.log 
1 
    >cat b.log 
3 
4 
    > 

は、終了コードが非ゼロ作りと「-e設定」を加えるようなスクリプトの残りを実行する上で引き続き動作するように表示されないだけで...

>cat how-to-exit-script-from-within-curly-braces.sh 
set -e 

{ 
    printf "%d\n" 1 
    exit 1 
    printf "%d\n" 2 
} | tee a.log 
{ 
    printf "%d\n" 3 
    printf "%d\n" 4 
} | tee b.log 

    >./how-to-exit-script-from-within-curly-braces.sh 
1 
3 
4 
    >cat a.log 
1 
    >cat b.log 
3 
4 
    > 

中括弧内からスクリプトを強制終了する方法はありますか? exitと中括弧には問題ありません

+1

スマイリーを除いて良いQ(私は気難しい; - >)しかし、S.O.あなたの間違ったシェル構文をスマイリーに変換していました。皆さんお元気で! – shellter

答えて

5

:bashで

exit | exit 
echo "Still alive" 

{ 
    exit 
} 
echo "This will never run." 

しかし、それはそこにexit、パイプに問題がある、とは、あなたがに実行しているものです既定では、パイプラインの各ステージはサブシェルで実行され、exitはそのサブシェルのみを終了できます。これはbashの特定のコードであり、かつ(例えば#!/bin/shsh myscriptを使用している場合など)shに動作しないこと

{ 
    printf "%d\n" 1 
    exit 1 
    printf "%d\n" 2 
} > >(tee a.log) 
echo "This will not run" 

注:あなたのケースでは、あなたはリダイレクトし、代わりにプロセス置換を使用することができます。代わりにbashを使用する必要があります。

+0

は美しく機能しました。非常に有益。ありがとうございました –

+1

FYI ... "set -o pipefail"もうまくいくようです。前のコマンドの1つが0以外のステータスで終了した場合、パイプラインコマンドの戻り値がゼロでないようにエラーを伝播するために使用されます。 "http://stackoverflow.com/a/19622300/2341218 –