BasicsAG BasicsAG - 6 months ago 22
Bash Question

BASH Script to Remove old files, and create a text file containing the count and size of total files deleted.

I am an Intern and was given a task of creating a BASH script to delete files in a directory older than 60 days and then exports a text file containing the number of files deleted as well as the amount of data removed. I am still attempting to learn BASH and have a one liner to remove files older than 30 days;

`find $DIR -type f -mtime -60 -exec rm -rf {}\;`

I am still actively attempting to learn BASH, so extra notes on any responses would be greatly appreciated!

P.S. I found Bash Academy , but looks like the site is incomplete, any recommendations for further reading in my quest to learn bash will also be greatly appreciated!


I would use the below script, say for the purpose :

  local totalsize=0
  echo " Removing files listed below "
  echo "${@}"
  sizes=( $(stat --format=%s "${@}") ) #storing sizes in an array.
  for i in "${sizes[@]}"
  (( totalsize += i )) #calculating total size.
  echo "Total space to be freed : $totalsize bytes"
  rm "${@}"
  if [ $? -eq 0 ]  #$? is the return value
  echo "All files deleted"
    echo "Some files couldn't be deleted"
export -f myfunc
find "$1" -type f -not -name "*" -mtime +60\
-exec bash -c 'myfunc "$@"' _ {} +
# -not -name "*" to prevent self deletion
# Note -mtime +60 for files older than 60 days.


chmod +x ./

And run it as

./deleter '/path/to/your/directory'


  1. Find [ manpage ] for more info.
  2. stat --format=%s gives size in bytes which we store in an array. See [ stat ] manpage.

feedback appreciated