Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

sponge as a shell script for non-interactive use, i.e., where we do not need to check the second file

   #!/bin/sh
   test $# = 1||exec echo usage: $0 file;
   test -f $1||exec echo $1 does not exist;
   test ! -f $1.tmp||exec echo $1.tmp exists;
   cat > $1.tmp;
   mv $1.tmp $1;


The script should probably be using `mktemp` instead of potentially overwriting uninvolved files (even if they have `.tmp` in the name).


When you do, just make sure you use the `--directory` option of `mktemp` to use the same directory as the final file. This makes sure both files are on the same filesystem, so `mv` is atomic (and faster).


And so I learned of mktemp today.

Just was intrigued, googled it, read about it and know it solves a problem I had elegantly. Some new tool in my belt from now on.

Thank you.


For a simple case like this I'd probably just go with something like tmp.$$.tmp.


You might need a -f on that final mv.

While you're at it, may as well create a backup of the $1 file.


sponge creates no backups

Never have I ever needed -f.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: