BasicsAG BasicsAG - 4 months ago 17
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!

Answer

I would use the below script, say deleter.sh for the purpose :

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

Do

chmod +x ./deleter.sh

And run it as

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

References

  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

Comments