括弧が中括弧の代わりに終了ステータスを返す理由

括弧が中括弧の代わりに終了ステータスを返す理由

私が知る限り、角かっこはコマンドをサブシェルで実行し、中括弧はコマンドをグループ化しますが、サブシェルで実行しないようにします。

かっこを使用して実行する場合:

no_func || (
    echo "there is nothing"
    exit 1
)

echo $?

これにより終了ステータスが返されます。

/Users/myname/bin/ex5: line 34: n_func: command not found
there is nothing
1

しかし、中かっこを使用すると、次のようになります。

no_func || {
    echo "there is nothing"
    exit 1
}

echo $?

終了ステータスを返しません。

/Users/myname/bin/ex5: line 34: no_func: command not found
there is nothing

しかし、なぜ1つは終了ステータスを返し、もう1つは返しませんか?

ベストアンサー1

コマンド実行トレース(set -x)を確認してください。校正器を含む:

+ no_func
./a: line 3: no_func: command not found
+ echo 'there is nothing'
there is nothing
+ exit 1

exit(サブ)シェルを終了します。中かっこはサブシェルを生成しないため、デフォルトのexitシェルプロセスが終了するため、実行ポイントに到達しませんecho $?

おすすめ記事