3 ms·
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;
by 1vuio0pswjnm7 5y ago
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;
- aix1 5y agoThe script should probably be using `mktemp` instead of potentially overwriting uninvolved files (even if they have `.tmp` in the name).
- progval 5y agoWhen 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).
- sdoering 5y agoAnd 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.
- tzs 5y agoFor a simple case like this I'd probably just go with something like tmp.$$.tmp.
- martinflack 5y agoYou might need a -f on that final mv. While you're at it, may as well create a backup of the $1 file.
- 1vuio0pswjnm7 5y agosponge creates no backups Never have I ever needed -f.