Reputation: 53
I have a bash that has 2 while loops, the first is an infinite loops that tracks some events, and the second reads a log file and does something when a specific line shows up:
#!/bin/bash
while [ 1 ]; do
...
done &
date=`date +%Y%m%d`
file="logs/$date.log"
tail -f $file | grep --line-buffered "ALERT" | while read line
do
...
done
This works great, my only issue is that each day after 00:00 the log rotates to a new day (this is sadly out of my control), how can I rerun the second while loop at 00:01 ? (log rotation is at first write but I don't mind losing a minute)
Using cron to kill everything and restart is not great because it also kills my first loop, so I was thinking there must be an intelligent way to do this from inside the script.
Upvotes: 2
Views: 469
Reputation: 27215
You can run the second loop inside a third loop. In each iteration, the that third loop restarts the second loop. Use sleep
to start the next iteration at 00:01.
#!/bin/bash
secondLoop() {
date=$(date +%Y%m%d)
file="logs/$date.log"
tail -f $file | grep --line-buffered "ALERT" | while read line; do
...
done
}
while true; do
...
done &
while true; do
secondLoop &
pidSecondLoop=$!
sleep $(($(date -d 'tomorrow 00:01' +%s) - $(date +%s)))
kill $pidSecondLoop
done
Upvotes: 1
Reputation: 5591
You can do it by introducing a function in your script. Add one function and move your while loop including codes into it and break the loop every day when time is greater than 00.01. Call the function from a infinite while loop as you are doing in your code. Once your break the while loop function will return and from infinite while loop you will call the function again with a new log file name.
Upvotes: 0