PIPESTATUS でパイプラインの各コマンドの終了ステータスを取得する

概要

$PIPESTATUS を使うことでパイプラインの各コマンドの終了ステータスを取得できる.
ただし,使用できる環境には制限がある模様.

$? で終了ステータスを取得する場合の問題点

$? で終了ステータスを取得した場合は一番右のコマンドの終了ステータスを取得する.

$ ./configure 2>&1 | tee _configure.log
$ echo $? # tee の終了ステータスが表示される

$PIPESTATUS を使う場合

上記のサンプルで ./configure の終了ステータスをみたい場合は $PIPESTATUS を使う.

$ ./configure 2>&1 | tee _configure.log
$ echo ${PIPESTATUS[0]} # configure の終了ステータスが表示される


また,全コマンドの終了ステータスをまとめて取得したい場合は以下のようにする.

$ echo ${PIPESTATUS[@]}

$PIPESTATUS を使ったサンプルコード

#!/bin/bash

./configure 2>&1 | tee _configure.log
if [ ${PIPESTATUS[0]} = 0 ]; then
    echo "configure: success"
else
    echo "configure: failed"
    exit 1
fi

make 2>&1 | tee _make.log
if [ ${PIPESTATUS[0]} = 0 ]; then
    echo "make: success"
else
    echo "make: failed"
    exit 2
fi

make check 2>&1 | tee _make_check.log
if [ ${PIPESTATUS[0]} = 0 ]; then
    echo "make check: success"
else
    echo "make check: failed"
    exit 3
fi

make install 2>&1 | tee _make_install.log
if [ ${PIPESTATUS[0]} = 0 ]; then
    echo "make install: success"
else
    echo "make install: failed"
    exit 4
fi

[余談] がんばるのがダルイ ログだけが欲しい場合

グループ化してまとめてログを出すだけでもいいかもしれない

{
./configure
make
make check
make install
} 2>&1 | tee _build.log