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
    Can you edit your question to show the while loop you've used? – ilkkachu Mar 21 '19 at 14:33
  • 3
    Have you considered a cron job? – eblock Mar 21 '19 at 14:38
  • I haven't considered a Cron job but the script must work on both OSX and Linux (Mint, in my case). – ATragicEnding Mar 21 '19 at 14:40
  • run a program every 5 minutes for 5 minutes means run the program continuously .... does it not? – jsotola Mar 22 '19 at 1:38
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

| improve this answer | |
  • I do need to run it continuously but I will have a look into cron jobs. Thank you! – ATragicEnding Mar 21 '19 at 14:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.