#!/bin/bash # 用法示例: # bash vmstat.sh # bash vmstat.sh 2 # bash vmstat.sh 2 10 # 默认间隔为 2 秒 interval="${1:-2}" # 如果提供了第二个参数, 则使用它作为采样次数;否则不附加 count if [ $# -ge 2 ]; then count="$2" vmstat_cmd=(vmstat -n "$interval" "$count") else vmstat_cmd=(vmstat -n "$interval") fi # 获取终端行数,若获取失败则默认 24 lines=$(tput lines 2>/dev/null || echo 24) # 每屏保留 2 行给表头和空行. 实际数据行数阈值 threshold=$((lines - 2)) "${vmstat_cmd[@]}" | awk -v th="$threshold" ' BEGIN { width[1] = 3 # r width[2] = 3 # b width[3] = 5 # swpd width[4] = 10 # free width[5] = 8 # buff width[6] = 8 # cache width[7] = 6 # si width[8] = 6 # so width[9] = 6 # bi width[10] = 6 # bo width[11] = 6 # in width[12] = 6 # cs width[13] = 6 # us width[14] = 6 # sy width[15] = 6 # id width[16] = 6 # wa width[17] = 6 # st width[18] = 6 # gu # 数据行计数器 line_cnt = 0 } NR == 1 { # 跳过 vmstat 第一行分组标题 next } NR == 2 { # 第二行是列名,保存为表头字符串,以便后续重复打印 ncols = NF header = "" for (i = 1; i <= ncols; i++) { w = (i in width) ? width[i] : 8 # 构建表头字符串(与输出格式一致) if (i > 1) header = header " " header = header sprintf("%*s", w, $i) } # 打印第一次表头 print header next } { # 数据行处理 # 检查是否需要重新打印表头(数据行数达到阈值) if (line_cnt >= th) { # 可选:打印一个空行分隔 print "" print header line_cnt = 0 } # 输出数据行 ncols = NF line = "" for (i = 1; i <= ncols; i++) { w = (i in width) ? width[i] : 8 if (i > 1) line = line " " line = line sprintf("%*s", w, $i) } print line line_cnt++ }'