Wait for stdout stream to finish and then add its contents to a file

Use sponge from GNU moreutils:

echo 'a lot of content' | command 1 | sponge file.txt

Or use a temporary file.


The simplest solution is probably sponge as @heemayl suggested. Alternatively, you could do something like this:

command > tmpfile && mv tmpfile watched_file

This will cause command to save its output in tmpfile, which will only be renamed to watched_file (the file your server is set up to watch) once the command has exited and only if it has exited successfully. To also rename it on failure, use:

command > tmpfile; mv tmpfile watched_file