Home > Mobile >  Shell script to Find ,Remove and print files removed
Shell script to Find ,Remove and print files removed

Time:05-31

I'm creating a script to maintain database backup directories that should retain files only seven days.

This is what i have created

set  vx
BACKUP_DIR=/mounts/prd
myarray=(`cat /u01/postgres_prod_server.txt`)

for SERVER in "${myarray[@]}"
do
   echo "   SERVER: $SERVER"
   if [ -d $BACKUP_DIR/$SERVER ]; then
      find $BACKUP_DIR/$SERVER/5431/ -type f -name '*.tar' -mtime  7 -exec rm -rf {} \; | tee /tmp/log.txt | wc -l | xargs echo "Files deleted:" >> /tmp/log.txt;
      find $BACKUP_DIR/$SERVER/5432/ -type f -name '*.tar' -mtime  7 -exec rm -rf {} \; | tee /tmp/log1.txt | wc -l | xargs echo "Files deleted:" >> /tmp/log1.txt;
   fi

done

Here is what i'm looking to do but its not working.

1.i'm unable to print what the find command is deleting and send to log file.

CodePudding user response:

-exec won't print anything, but you can use -print option to do that. See https://unix.stackexchange.com/a/503530/527050.

Also, ...| tee /tmp/log.txt will truncate the log file, so you need to add option -a to keep previous log.

Final script looks like this: (The path of a log file is used twice, so you may want to store it in a variable.)

LOG_FILE=/tmp/log.txt
SEARCH_DIR="$BACKUP_DIR/$SERVER/5431/"

find "${SEARCH_DIR}" -type f -name '*.tar' -mtime  7 \
  -exec rm -rf {} \; -print | \
  tee -a "${LOG_FILE}" | \
  wc -l | \
  xargs echo "Files deleted:" >> "${LOG_FILE}";
  • Related