While doing some work, I found this "sponge" command that does the same as "tee", but could not find when it is better to use one or the other.
Can someone explain?
While doing some work, I found this "sponge" command that does the same as "tee", but could not find when it is better to use one or the other.
Can someone explain?
No one of them soak up stderr; only stdout. 'tee' writes stdin on stdout and files. 'sponge' writes stdin only on a file; without errors, no output. (i.e: Unlike 'tee', 'sponge' doesn't write on stdout). Besides,
"sponge soaks up all its input before opening the output file"
(from its manual)
This difference between them is extremely relevant: 'tee' "reads a byte", and "writes that byte"; 'sponge' waits to receive all the input, and then, writes it.
in practice there is a huge difference if your doing iterative processing; as tee will read byte by byte, you may end up with blank file due instisfatory redirects if your source file is also the target file. Sponge, will read all the input before starting to write to an open file.
tf=/tmp/simple
jq -n '.name="Doe"' > $tf
cat $tf
> { "name": "Doe" }
jq '.name' $tf | tee $tf
cat $tf
>
> #no output, file is blank
tf=/tmp/simple
jq -n '.name="Doe"' > $tf
cat $tf
> { "name": "Doe" }
jq '.name' $tf | sponge $tf
cat $tf
> "Doe"
> # we got the expected output