I'm not used to linux scripting and this is the first time I'm working on it so I'm struggling with the following problem:
Code:
while [ $pct -gt 80 ]; do
flag=1;
ls -tr | while read file; do
if [[ $file =~ .+\.log[0-9]+ ]]; then
printf "File deleted:\n";
stat $file;
rm -r $file;
flag=1;
break;
else
flag=0;
fi;
done;
if [ $flag -eq 0]; then
break;
fi;
pct= # get the new pct;
done;
The operation is to delete certain log files as captured by the above regular expression, in order of oldest files first and hence I'm using ls -tr. I'm iterating over the list of files using the while loop and if any file matches with the given regex, I'm deleting it. After every deletion I'm checking the percentage of the application file system used and if it is greater than 80% (as shown in outer while loop condition), I repeat the process.
Now often, even after deleting the files, the percentage used doesn't go below 80%, even though no files with the given regex pattern is left and I cannot delete the other remaining files in the same folder. So, it goes into an infinite loop and hence I'm trying to use a flag variable to break the infinite loop in such cases. However, since I'm using pipe to iterate over the files, it becomes a sub-shell or a child process and the flag variable is not available (updated value of flag from sub shell does not reflect in parent shell) in the parent process (it's what I read in an article about piping) and thus the infinite loop is never broken. Can anyone please suggest a fix around this or an alternate logic?