BASH logging to file, limit lines

BASH Gurus: Anyone know how to append continuous output command appending to a file, but limit that file to no more than 20 lines? The program I have running is simply monitoring my UDP port 53 for incoming packets endlessly. I just need to keep this file from going over 20 lines. Once the file reaches 21 lines, the 1st line of the file should be removed and so on.

I have used sed, which does this perfectly:

sed "1d" log.txt

Here is the command below, when ran, it continuously logs the incoming packets

netcat -ul -p 53 >> log.txt

I just don't know how to combine these in one command (piping would be great). Open to any ideas.

First post on the forums, thanks and hello to all! :stuck_out_tongue:

Assuming that log.txt contains 20 lines of text when you start the following script:

netcat -ul -p 53 | while IFS='' read -r line
do	sed 1d log.txt > _log.txt
	{ cat _log.txt; printf '%s\n' "$line"; } > log.txt
done

might come close to doing what you want.

1 Like

I am very grateful for your reply, that did it perfectly! I simply used a

LINECOUNT=$(wc -l < "log.txt")

to grab the number of lines in the file and put on space in any remaining. Easy enough to parse out the spaces and display data

I cannot thank you enough Don, many, MANY thanks! :b::b::b:

While Don Cragun's fine proposal works brilliantly, it preserves the line count on hand, be it 8 or 800. Try piping into this (shamelessly stolen from Don Cragun) to make log.txt exactly 20 lines long, no matter what its size be:

while IFS='' read -r line
  do    tail -19 log.txt > _log.txt
        { cat _log.txt
          printf '%s\n' "$line"
        } > log.txt
  done
1 Like