|&パイプについて

|&パイプについて

バッシュマニュアルからhttps://www.gnu.org/software/bash/manual/html_node/Pipelines.html それは次のように言います:

|&''を使用すると、標準エラーがcommand1標準出力に加えて標準command2入力にパイプされます2>&1 |

コミュニティに関する私の質問は、それが実際に何を意味するのかです。なぜ何もしないと思うのかを示すためにテストしました。

ここでは動作するループを作成し、最後の行にエラーが発生しました。

items="frog cat"
for item in $items
do 
echo $item
done

for item i will make error this line

したがって、マニュアルで暗示するのは、|&を使用しない限り、stderrは次のコマンドにパイプされるため、stdoutに出力されないことです。だからテストしてみました:

## this shows a regular pipe without &.  As you can see stderr gets written anyway
$ ./testing.sh  | grep error
./testing.sh: line 7: syntax error near unexpected token `i'
./testing.sh: line 7: `for item i will make error this line'

## this shows a pipe with |& in it.  
$ ./testing.sh  |& grep error
./testing.sh: line 7: syntax error near unexpected token `i'
./testing.sh: line 7: `for item i will make error this line'

はい、stderrorはとにかく次のパイプコマンドに書き込まれます&|。それでは、そのポイントは何ですか|&

ベストアンサー1

stderr は「とにかく次のパイプコマンドへの書き込み」ではなく、デフォルトで端末に入る stderr に書き込まれます。

Bashリファレンスマニュアルは次のように述べています。

の略です2>&1 |。標準エラーを標準出力に暗黙的にリダイレクトすることは、 command1 で指定されたリダイレクトの後に行われます。

これは、stderrがパイプを介して送信される前にstdoutにリダイレクトされることを意味します。

$ cat stderr.sh
#!/usr/bin/env bash


echo 'This is an error' >&2
echo 'This is not'

これを実行すると、stdoutとstderrに出力が表示されます。

$ ./stderr.sh
This is an error # This is displayed on stderr
This is not # this is displayed on stdout

stdoutをリダイレクトすると、/dev/nullstderrのみが表示されます。

$ ./stderr.sh >/dev/null
This is an error

同様に、stderrをstdoutにリダイレクトすると、/dev/null次のようになります。

$ ./stderr.sh 2>/dev/null
This is not

ここでは、このsedコマンドを使用してパイプを通過する方法をさらに詳しく説明できます。

$ ./stderr.sh | sed 's/^/Via the pipe: /'
This is an error
Via the pipe: This is not

$ ./stderr.sh |& sed 's/^/Via the pipe: /'
Via the pipe: This is an error
Via the pipe: This is not

最初の例では、エラーはVia the pipe:パイプを通って移動しないため、エラーの前に付着しません。これは第2の例でも同様である。

おすすめ記事