Shell script to remove all files from a folder in quick time

Dear Readers,

Trust you are doing well.

I am writing this post to share you sample shell script code which will help to remove all files under particular folder in quick time.

This requirement normally comes when, we have to remove huge number of old files under folders which have not been housekeeped for quite some time.

I had a urgent request to remove *.aud files from one of UAT server which was not housekeeped in 2 years.

Below is the sample shell script I used to resolve this issue. This script you can put it in any folder and requires complete path of directory to be housekeeped as a input. Using this script, I was able to remove 7 million files in less than 15 minutes.

Sample script:

#!/bin/bash

# Author: Adityanath Dewoolkar
# Date: 07 September 2023
# Description: Shell script to quickly remove all files from a folder
# Purpose: Created for removing huge number for aud files from UAT servers which were not housekeeped.
# Version:  v1 - initial

##set -x

########################
## ENV SETTINGS
########################

echo "Enter directory path to be cleaned:"
read DIR

ls -f $DIR > /tmp/remove_files

for i in `cat /tmp/remove_files`
do
echo "rm -f $i" >> /tmp/remove_files_current
done

mv /tmp/remove_files_current $DIR

cd $DIR

split -l 5000 remove_files_current final

ls final* > final_remove_files_current.txt

for i in `cat final_remove_files_current.txt`
do
nohup sh $i &
done

cnt=`cat /tmp/remove_files | wc -l`

echo "Total number of files removed: $cnt"

rm final*
rm remove_files_current
rm /tmp/remove_files

exit 0

Scipt can also be downloaded from below link.

Hope so u will find this post very useful:-)

You can refer my post on non-dictionary objects statistics gathering here.

Regards,
Adityanath.

2 replies

  1. If you delete the entire directory, try it
    perl -e ‘unlink for (“*.aud” )’
    or
    find . -name “*.aud” -type f -mtime +30 | sort -t”_” -k4 -n | xargs -P 10 /bin/rm -f

  2. If you delete the entire directory, try it
    perl -e ‘unlink for ( <*.aud> )’
    or
    find . -name "*.aud" -type f -mtime +30 | sort -t"_" -k4 -n | xargs -P 10 /bin/rm -f

Leave a comment