Skip to content
Advertisement

shell difference between redirect position

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 from stdio.h in C, cout << … in C++, print in many high-level languages), then its output is buffered: characters accumulate in a memory zone which is called a buffer; when there’s too much data in the buffer, the contents of the buffer is printed (it’s “flushed”) and the buffer becomes empty (ready to be filled again). If your program doesn’t produce much output, it may not have filled its buffer yet.

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement