Search code examples
terminaltail

why does tail -F -n 1 myfile.txt print .all. the contents of myfile as it gets updated?


What I'm trying to do is really simple - I want to monitor a file and print its last line to the screen as the file gets updated. From what I know,

tail -F -n 1 myfile.txt

should do exactly that. However, I get strange behaviour: With the "original" myfile.txt, the command works fine and only the last line is printed to the screen. However, as soon as I alter myfile.txt by appending new lines of text, the entire contents of myfile.txt are printed - rather than just the very last line.

I have never used tail before and I might just be getting something terribly wrong here, but surely that's not the expected behaviour? I purposefully use the -F flag so I can manually alter myfile.txt - could that be the reason for it not working?

Help is very much appreciated... Thanks so, so much!


Solution

  • No, that's the way it's meant to work, -n 1 is the initial behaviour, printing only the last line, but -F follows the file beyond that point, and states quite clearly:

    output appended data as the file grows;

    In other words, it outputs all the appended data that's gone to the file.

    If you examine the source code, you'll notice the main() function first processes the -n option and, only at the end, does it call tail_forever(), in which there is no mention of the argument supplied with -n.

    If you execute:

    ( echo 1; echo 2; echo 3 ) >qq
    

    in one window then start up a tail in another:

    tail -F -n 1
    

    you should get only the line with 3.

    If you then return to the original window and execute:

    ( echo 4; echo 5; echo 6 ) >>qq
    

    your second window should just output the new lines (and all three of them).

    If your second window gives you all six of the lines, it's broken.