user3085747
user3085747

Reputation: 65

Is there any way to output and log number of files deleted from shell script

I have a shell script file called somefile.sh and it has the code something like below,

somefile.sh

find /xxx/yyy/* -mtime +30 -exec rm {} \;
find /xxx/zzz/* -mtime +30 -exec rm {} \;
find /xxx/xyx/* -mtime +30 -exec rm {} \;
find /xxx/xzx/* -mtime +30 -exec rm {} \;

And this runs in a cron by daily basis,

Now I want to set up a log file for this, like for each shell script I want to output my each command results to a file with and then ,

Can anyone plese help me to solve this. Thanks in advance.

Upvotes: 1

Views: 2881

Answers (2)

Walter A
Walter A

Reputation: 19982

Let your find print what it deletes

find /xxx/zzz/* -mtime +30 -print -exec rm {} \;

or

find /xxx/zzz/* -mtime +30 -exec echo Removing +30 days file {} \; -exec rm {} \;

Next you can filter the output (wc -l or grep -c) the way you want.

Upvotes: 1

BMW
BMW

Reputation: 45243

Build a folder list with expired day.

cat folder.list

/xxx/yyy  30
/xxx/zzz  30
/xxx/xyx  7
/xxx/xzx  14

update somefile.sh

LOG=/var/tmp/LOG

while read folder day X
do
    echo "Working on folder ${folder} .."
    find ${folder}/* -mtime +${day} -type f |while read line
    do
        echo "removing $line ...."
        rm ${line}
    done
done <folder.list >> $LOG

updated with new request (count the delete files)

#!/usr/bin/bash

LOG=/var/tmp/LOG

while read folder day X
do
    echo "Working on folder ${folder} .."
    i=0
    find ${folder}/* -mtime +${day} -type f |while read line
    do
        echo "removing $line ...."
        rm ${line}
        ((i++))
    done
    echo "Totally deleted $i files in folder $folder"
done <folder.list >> $LOG

Upvotes: 2

Related Questions