How keep last 50 lines in logfile

command linelogstail

I try to keep last 50 lines in my file where I save temperature every minute. I used this command:

tail -n 50 /home/pi/Documents/test > /home/pi/Documents/test

But the result is empty test file. I thought, it will lists last 50 lines of test file and insert it to test file. When I use this command:

tail -n 50 /home/pi/Documents/test > /home/pi/Documents/test2

it is working fine. There is 50 lines in test2 file.

Can anybody explain me where is the problem?

Best Answer

The problem is that your shell is setting up the command pipeline before running the commands. It's not a matter of "input and output", it's that the file's content is already gone before tail even runs. It goes something like:

  1. The shell opens the > output file for writing, truncating it
  2. The shell sets up to have file-descriptor 1 (for stdout) be used for that output
  3. The shell executes tail.
  4. tail runs, opens /home/pi/Documents/test and finds nothing there

There are various solutions, but the key is to understand the problem, what's actually going wrong and why.

This will produce what you are looking for,

echo "$(tail -n 50 /home/pi/Documents/test)" > /home/pi/Documents/test

Explanation :

  • $() is called command substitution which executes tail -n 50 /home/pi/Documents/test
  • the quotation marks preserve line breaks in the output.
  • > /home/pi/Documents/test redirects output of echo "$(tail -n 50 /home/pi/Documents/test)" to the same file.
Related Question