This is because bash processes the redirection with the >
first, deleting the contents of the file. Then it executes the command. Were you to use >>
, the last 50 lines would be appended to the end of what's currently in the file. In this case, you'd have the same 50 lines repeated twice.
The command works as expected when redirecting to a different file. Here is one way to write the last 50 lines of a file to a file of the same name:
tail -50 /home/pi/Documents/test > /home/pi/Documents/test2 && mv /home/pi/Documents/test2 /home/pi/Documents/test
This first writes the last 50 lines to a temporary file, which is then moved using mv
to replace the original file.
As noted in the comments, this won't work if the file is still open. Moving the file also creates a new inode and may change ownership and permissions. A better way to do this using a temporary file would be:
tail -50 /home/pi/Documents/test > /home/pi/Documents/test2 ; cat /home/pi/Documents/test2 > /home/pi/Documents/test
The temporary file can also be removed, though each time this happens its contents will be overwritten.
logging
module