<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>sigpipe on tac lifelog</title>
    <link>https://tro3373.github.io/tags/sigpipe/</link>
    <description>Recent content in sigpipe on tac lifelog</description>
    <image>
      <title>tac lifelog</title>
      <url>https://tro3373.github.io/favicon.png</url>
      <link>https://tro3373.github.io/favicon.png</link>
    </image>
    <generator>Hugo</generator>
    <language>ja</language>
    <lastBuildDate>Tue, 27 Oct 2026 13:39:45 +0900</lastBuildDate>
    <atom:link href="https://tro3373.github.io/tags/sigpipe/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>bash のパイプが返す終了コードと SIGPIPE</title>
      <link>https://tro3373.github.io/posts/2026/2026-10-27-bash-pipeline-exit-status-sigpipe/</link>
      <pubDate>Tue, 27 Oct 2026 13:39:45 +0900</pubDate>
      <guid>https://tro3373.github.io/posts/2026/2026-10-27-bash-pipeline-exit-status-sigpipe/</guid>
      <description>&lt;h2 id=&#34;結論&#34;&gt;結論&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;パイプの終了コードは、既定では末尾のコマンドのもの。&lt;code&gt;set -o pipefail&lt;/code&gt; を立てると、最後に非 0 で終わったコマンドのものになる&lt;/li&gt;
&lt;li&gt;&lt;code&gt;||&lt;/code&gt; と &lt;code&gt;if&lt;/code&gt; はパイプ全体の終了コードを見る。&lt;code&gt;cmd | grep -v X || true&lt;/code&gt; は cmd の失敗も 0 にし、&lt;code&gt;if cmd | grep -q X&lt;/code&gt; は取得の失敗を「一致なし」と同じ偽にする&lt;/li&gt;
&lt;li&gt;読み手が終わった後に書き手が書くと、書き手は SIGPIPE で 141 になり、&lt;code&gt;pipefail&lt;/code&gt; がそれを全体の終了コードにする。&lt;code&gt;| head&lt;/code&gt;、&lt;code&gt;| grep -q&lt;/code&gt;、stdin を読まない読み手で起き、出力が小さくても書く順番しだいで起きる&lt;/li&gt;
&lt;li&gt;&lt;code&gt;mapfile &amp;lt; &amp;lt;(cmd)&lt;/code&gt; はパイプではないので、cmd の失敗はどこにも残らない&lt;/li&gt;
&lt;li&gt;判定に使う出力は先に変数へ取り、here-string で渡す。fallback 付きのコマンドは、成功したときだけ stdout に出す&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;以下は GNU bash 5.3.15 / GNU coreutils 9.11 / GNU grep 3.12 / Linux x86_64 で実測した。回数を書いたものはタイミングで決まるので、環境によって数字が変わる。&lt;/p&gt;
&lt;h2 id=&#34;前提-パイプの終了コードはどのコマンドのものか&#34;&gt;前提: パイプの終了コードはどのコマンドのものか&lt;/h2&gt;
&lt;p&gt;&lt;img alt=&#34;既定ではパイプの終了コードは右端のコマンドのもので、pipefail を立てると最後に非 0 で終わったコマンドのものになる&#34; loading=&#34;lazy&#34; src=&#34;https://tro3373.github.io/posts/2026/2026-10-27-bash-pipeline-exit-status-sigpipe/fig-status.webp&#34;&gt;&lt;/p&gt;</description>
    </item>
  </channel>
</rss>
