I want to write a shell-Script for my Raspberry Pi to permanently ping a specific host but only keep the last 20 results in a text file.
So my idea was to redirect the ping output to a text file and write a loop to permanently limit said file to 20 lines.
My idea was to output the ping results to a file and tail it with an endless loop:
ping ServerX.domain.com -i 5 -D 1>/home/user/Desktop/Ping.txt &
while :
do
tail /home/user/Desktop/Ping.txt -n 20 >/home/user/Desktop/Ping.txt
done
This somehow keeps completely erasing the file content? So I have to redirect the content to a variable and then rewrite said variable to the file:
ping ServerX.domain.com -i 5 -D >/home/user/Desktop/Ping.txt &
while :
do
PingContent=$(tail /home/user/Desktop/Ping.txt -n 20)
echo "$PingContent" >/home/user/Desktop/Ping.txt
sleep 4
done
This seems to work quiet well, but every now and then some unreadable null-characters appear in the last line of my file. I guess this happens when both commands try to write into the Ping.txt at the same time. How may I avoid this?