Skip to main content

How to create a shell script to delete a particular file in loop [Resolved]

Actually I am intending to create a shell script executing which should delete particular files/folders continuously say every 5 seconds which is continuously being generated by a application

[ Below data being used is a dummy so that it becomes easy to understand and probably help others too in general ]

Target App Package name - com.example.mypackage

Target App Launch Activity Name - com.activity.launcher

Target App's files to be deleted - /sdcard/Android/data/app/log1 , /sdcard/Android/data/app/log2

Deletion Interval : Every 5 Seconds

Start Trigger Point : Only After i execute the shell script

End Point : Deletion Loop Process Should end automatically after target App is no longer active ( Hence mentioned activity Name above )


Question Credit: Badal Singh
Question Reference
Asked September 10, 2019
Posted Under: Unix Linux
21 views
1 Answers

Here is a short bash script I came up with. Note you will need to replace logger\.sh in the grep statements with the name of the process that you want to monitor. In this case it is checking for a process named "logger.sh" and grabbing the PID.

#!/bin/bash

pid=$(ps aux | grep "logger\.sh" | head -n 1 |  awk '{print $2}');

if [ "$pid" != "" ] 
    then
    pidFound=1;
    while [ "$pidFound" = 1 ]
    do
        rm /sdcard/Android/data/app/log1;
        rm /sdcard/Android/data/app/log2;
        sleep 5;
        pid=$(ps aux | grep "logger\.sh" | head -n 1 |  awk '{print $2}');
        if [ "$pid" != "" ]; then
            pidFound=1;
        else
            pidFound=0;
            break
        fi
    done
fi

credit: john doe
Answered September 10, 2019
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA