Bash adding to file inside and outside of loop
What is the difference between these two commands?
while true; do date; sleep 1; done > /tmp/log
against
while true; do date >> /tmp/log; sleep 1; done
Both attach to the same timeline file, but it looks like both do it differently.
I thought the first one would not add anything to the file, because all attachment to the file will happen after the end of the loop, and since the loop is infinite, nothing will ever be written to the file. It is also possible that the first is appended to the file when only one is used >
?
source to share
In version 1, the output is immediately appended to the file because the command date
flushes its output when it exits, which writes everything to the standard output file.
Version 1 is not appended to the file. It opens the file descriptor of the file when the loop starts and empties the file when it does. This handle remains open for the entire loop and is inherited by every command in the loop as standard output. Since it doesn't close or open before every command, the file is not truncated every time - they are simply written to the current position in the file.
source to share
For the first team
while true; do date; sleep 1; done
regarded as a "block". Anything that the block outputs is printed on stdout
. You are simply redirecting the output of that block to a file.
Imagine you had the following shell script:
#!/bin/bash
while true; do date; sleep 1; done
And now you run
script.sh > /tmp/log
You also expect the log file to be constantly written to.
source to share
This command:
while true; do date; sleep 1; done > /tmp/log
opens the file immediately (before the loop ever starts) (and truncates any existing content in the file), and commands that are executed inside the loop inherit the open file descriptor (fd), and any output is written to that fd as output will be executed.
This command:
while true; do date >> /tmp/log; sleep 1; done
opens the file once each time through the loop (just before running the command date
). The operator >>
opens the file in append mode, so the existing contents of the file are not truncated.
source to share