作ったもの
きっかけ
ECSタスク定義をjqでゴニョゴニョしているときにコマンドラインで読み込んだファイルをリダイレクトで同じファイルに書き出したいなと思ったのがきっかけでsponge(1)を知ることになりました。
https://www.gnu.org/software/bash/manual/html_node/Redirections.html
3.6.2 Redirecting Output Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size.
bash*1ではリダイレクトで出力する際に既にファイルが存在していたら、ファイルの中身が空になってしまいます。この問題を回避するために編集後のファイルの中身を一時ファイルに逃がし、後にそれをコピーする必要があります。その作業を楽にするのがmoreutilsのsponge(1)です。
ソースコードは1ファイルの数百行程度のCで実装されていたため、興味本位でGoっぽく味付けしてみました。 バッファサイズやシグナルハンドリングの挙動等まで揃えるモチベーションはなかったため、そのあたりはラフな感じになっています。
合わせて読みたい
- moreutils
- sponge(1) — moreutils — Debian testing — Debian Manpages
- moreutils/sponge.c at master · stigtsp/moreutils · GitHub
- Redirections (Bash Reference Manual)
*1:他の多くのシェルでも、おそらく同じ挙動をするのではないでしょうか