0

Good morning !

I am trying to run the following script every X minutes for Y minutes. Basically, this script outputs a logcat for 5 minutes and checks for files older than 30 minutes to remove them. So far, I haven't found a way to loop this script every 5 minutes beside using watch -n 300 Script.sh

  timeout 5m adb shell logcat > ~/ADB/"$(date +%F_%H-%M-%S)".txt

  find ~/ADB/ -type f -name '*.txt' -mtime +30m -exec rm {} \;

So far, I have tried with a while loop but it stacks the script every second. The only way it works is using a watch -n 300 Script.sh in a terminal. It lets the script run every 5 minutes for 5 minutes (Then check for files older than 30 minutes to remove them) but I would like to have the whole thing in a single script I can run at bootup.

Edit :

while true;
do
timeout 5m adb shell logcat > ~/ADB/"$(date +%F_%H-%M-%S)".txt
find ~/ADB/ -type f -name '*.txt' -mtime +30m -exec rm {} \;
done

1 Answers1

0

Probably a better task for a cron job since it seems like you really want it to run continuously but if you do need to set an end time and want to run a continuous loop you could do something like the following:

#!/bin/bash

while getopts i:d: opt; do
    case $opt in
        i)  interval=$OPTARG;;
        d)  duration=$OPTARG;;
    esac
done

now=$(date '+%s')
interval=$((interval*60))
end=$(date -d "+ $duration minutes" '+%s' || date -v+"$duration"M '+%s')

until ((now>=end)); do
    stuff

    sleep "$interval"
    now=$(date '+%s')
done

You would run this like:

./script.sh -i 5 -d 60

(Which would run the script every 5 minutes for a total of 60 minutes)

NOTE: This does not take into account the amount of time your code takes to run. It will simply wait interval time between runs

jesse_b
  • 37,005