sponge can “soak up” stdin and write it atomically to a file, enabling one to do cat f|sponge a. I want to know how exactly it accomplishes this. How does it know when the input is finished?

  • 2
    What do you mean? The same way every other program knows (e.g. cat f | wc or cat f | grep foo or whatever), why would you expect sponge to be special? – terdon Nov 22 '18 at 19:31

strace or similar will show the system calls used by sponge, which is probably to write(2) the input read(2) from standard input out to a temporary file, and then to rename(2) that temporary file to the desired output filename when the input ends. The input ends when a read(2) call fails or returns 0 (which indicates end-of-file) at which point sponge can do the rename.

  • And when the rename() fails with EXDEV when /tmp is on a different file system, it ends up copying the data again into the destination file. You can avoid that by setting TMPDIR to $(dirname target-file) or use ksh93's >; operator instead of sponge which does that automatically (and also doesn't override the target file if the redirected command failed). – Stéphane Chazelas Nov 22 '18 at 21:06
  • >; ? mind blown. – glenn jackman Nov 23 '18 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.