编写脚本实现监测指定文件夹的磁盘空间。
===========================================================
## 脚本逻辑介绍
用户通过 --path 选项输入检测的文件夹路径。如果不输,则默认监测 /home 文件夹下的磁盘空间。
用户可通过 --help 命令查看脚本描述。如果用户输错了打印 help 信息。
用户可通过 --depth 选项指定检测文件夹的深度,默认检测 2 层。
===========================================================
#!/bin/bash ## variable for executor path="/home" depth="2" function helpu { ## print help info echo " " echo "[disk monitor]" echo "Usage: $0 --depth N directory_path" echo " " exit } function parser { ## parse the input parameters if [ $# -gt 3 ]; then echo -e " Error: The number of parameters is wrong, please input the correct parameters number first" helpu exit 1 fi while [ True ]; do if [ "${1}" = "--help" -o "${1}" = "-h" ]; then helpu elif [ "${1}" = "--depth" -o "${1}" = "-d" ]; then depth="${2}" shift 2 elif [ "${1}" != "" ]; then path=${1} break elif [ "${1}" == "" ]; then break else echo "Unexpected error happened" exit 1 fi done } function executor { ## real monitor executor DATE=$(date '+%m%d%y') du -d "${depth}" "${path}" | sort -rn | sed '{21,$D; =}' | sed 'N; s/ / /' |
gawk '{printf $1 ":" " " $2 " " $3 " "}' | tee /tmp/disk_monitor_${DATE}.report } parser "${@}" executor
该脚本和 lazy_find 逻辑类似,不同点主要有 sed,gawk 等命令的使用。sed 详细介绍可看这里,gawk 详细介绍可看这里。