LoginSignup
4
3

More than 3 years have passed since last update.

パイプ処理の終了ステータスの取得方法

Last updated at Posted at 2019-10-22

パイプ処理の終了ステータスの取得

パイプ処理を行った場合、特殊変数 $? に設定される値は
一番最後に実行されたコマンドの終了ステータスとなる。

例)

sample.sh
#!/bin/bash

$ exit 0 | exit 1 | exit 2
$ echo $?
2

パイプ処理の途中のコマンドの終了ステータスの取得方法

パイプ処理の最後のコマンドの終了ステータスではなく、
パイプ処理の途中で実行しているコマンドの終了ステータスを取得したい場合の方法

特殊変数 $PIPESTATUS (配列)を使用することで、
パイプ処理で実行された各コマンドの終了ステータスを取得することができる (※bash 限定で ksh は不可)

sample.sh
#!/bin/bash

$ exit 0 | exit 1 | exit 2
$ echo ${PIPESTATUS[@]}
0 1 2

# $PIPESTATUS [@]で配列の全要素を出力している
# @を数字に変えれば指定した位置のコマンドの終了ステータスを取得可能

コマンドの実行結果と各コマンドの終了ステータスの両方取得したい

コマンドを実行した後にパイプ処理でPIPESTATUSをexitで終了ステータスを指定する

sample.sh
#!/bin/bash

result=`exit 1 | echo "test"`
echo $?
echo $result

result=`exit 1 | echo "test2" ; exit ${PIPESTATUS[0]}`
echo $?
echo $result

#出力結果
0
test
1
test2

※備忘録のためわかりにくい部分ありましたらコメントください

4
3
0

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
4
3