1. 程式人生 > 實用技巧 >shell 指令碼之 disk_monitor

shell 指令碼之 disk_monitor


編寫指令碼實現監測指定資料夾的磁碟空間。 =========================================================== ## 指令碼邏輯介紹 使用者通過 --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 "\nError: 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/\n/ /' | gawk '{printf $1 ":" "\t" $2 "\t" $3 "\n"}' | tee /tmp/disk_monitor_${DATE}.report } parser "${@}" executor
該指令碼和 lazy_find 邏輯類似,不同點主要有 sed,gawk 等命令的使用。sed 詳細介紹可看這裡,gawk 詳細介紹可看這裡。