Is there any difference between these 2 lines?
for i in $(seq 1 10); do echo $i - `date`; sleep 1; done >> /tmp/output.txt for i in $(seq 1 10); do echo $i - `date` >> /tmp/output.txt ; sleep 1; done
Because Robert told me that the first one only makes the I/O OP outside the for loop.
But if I type tail -f /tmp/output.txt
this is behaving exactly the same way.
Advertisement
Answer
They do the same if they succeed. However, there might be notable differences if they fail for whatever reason.
The first one:
for ...; do # things done >> file
This will redirect to the file supposedly after the loop is done. However, it might happen whenever Bash decides to flush the buffer.
Imagine something fails after the iteration number 3: you cannot tell what has been stored after in the file.
The second one:
for ...; do # things >> file done
This will redirect to the file on every iteration.
Imagine something fails after the iteration number 3: you are sure the first two loops have been stored properly in the file.
From How to redirect output from an infinite-loop program:
If your program is using the standard output functions (e.g.
puts
,printf
and friends fromstdio.h
in C,cout << …
in C++,
Also, from the answer you link:
Placing the redirection operator outside the loop doubles the performance when writing 500000 lines (on my system).
This makes sense: if you have to flush on every loop, it takes more time than letting Bash flush whenever it finds it convenient. It is easier to write five lines at the time than a line every single time.