BASH脚本删除旧文件,并创建一个文本文件,其中包含已删除的文件总数和大小。

时间:2016-07-19 17:10:14

标签: linux bash shell memory memory-management

我是一名实习生,负责创建一个BASH脚本来删除超过60天的目录中的文件,然后导出一个文本文件,其中包含已删除文件的数量以及删除的数据量。我仍在尝试学习BASH,并且有一个衬垫可以删除超过30天的文件;

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

我仍在积极尝试学习BASH,因此非常感谢任何回复的额外说明!

P.S。我找到了Bash Academy,但看起来该网站不完整,任何在我学习bash的过程中进一步阅读的建议也将不胜感激!

1 个答案:

答案 0 :(得分:1)

我会使用以下脚本,为此目的说 deleter.sh

#!/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.

待办事项

chmod +x ./deleter.sh

将其作为

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

<强>参考

  1. 查找[ manpage ]了解详情。
  2. stat --format=%s给出了我们存储在数组中的字节大小。请参阅[ stat ]联机帮助页。
  3. 反馈意见

相关问题