If we redirect a command such as sar -r 1> a_file.txt how does this works with opening, writing the output of the command and closing the file?

In other words, how does redirecting a command output works in the background opening writing and closing the file? (specially a command such as the above that periodically and continually sends data to output)

I am wondering if there is some cacheing involved and if some flushing (writing the contents to the file) occurs at the end

  • The file is opened, then the command runs and only when the command ends, the file is closed. But what is your actual problem?
    – pLumo
    Jun 9, 2020 at 13:59
  • My actual problem is quite complex but it is basically I am redirecting a command to a file, the file gets created but with 0 bytes. I am guessing perhaps it is because it was not correctly closed so I want to understand the mechanics of redirecting Jun 9, 2020 at 14:08
  • that is the normal behavior.
    – pLumo
    Jun 9, 2020 at 14:10
  • so, does the "flushing" of data occurs at the end when the command ends? Jun 9, 2020 at 14:11
  • no, it writes to the file when output comes. You can test with something like this: ( sleep 5; echo 1; sleep 5; echo 2; ) > testfile and in a second terminal tail -f testfile
    – pLumo
    Jun 9, 2020 at 14:13

1 Answer 1


File redirection (<input, >output, 2>error) is handled by the parent shell. The executed command (sar in your example) sees only the file handle (0 => STDIN, 1 => STDOUT, 2 => STDERR) and reads/writes via the file handle. The executed program doesn't even know that anything's redirected.

Since the file (> a_file.txt) is opened by the parent shell, when the executed program exits, the parent shell simply closes it, which automatically flushes any buffers.

  • so there is only one flush at the end? Jun 9, 2020 at 20:45
  • One flush is all it takes. See man fflush
    – waltinator
    Jun 10, 2020 at 2:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.