NASutils Knowledge BaseUnofficialPolski

Bash · projectA live dashboard of the NAS

This script turns the SSH window into a live dashboard of the NAS. Every 2 seconds it redraws the CPU with its load and temperatures, the memory, each data volume and the rate of each network port, and it ends when you press q.

Programming on the NAS › Bash in 30 lessons

 NAS stats           TBS-h574TX                              2026-11-27 09:30:00

┌─ CPU ────────────────────────────────┐┌─ Memory ─────────────────────────────┐
│ 12th Gen Intel Core i5-1235U         ││ Total        15.4 GiB                │
│ 10 cores, 12 logical processors      ││ In use        5.6 GiB                │
│ Load      1.17  0.90  0.88           ││ Available     9.8 GiB                │
│ ██░░░░░░░░░░░░░░░░░░░░░░   9 %       ││ Cache         6.5 GiB                │
│ CPU       53 °C                      ││ ████████░░░░░░░░░░░░░░░░  36 %       │
│ System    34 °C                      ││                                      │
└──────────────────────────────────────┘└──────────────────────────────────────┘
┌─ Volumes ────────────────────────────────────────────────────────────────────┐
│ CACHEDEV1_DATA  ██████░░░░░░░░░░░░░░░░░░░░░░░░   281.8 /  1327.1 GiB  21%    │
│ CACHEDEV2_DATA  ████░░░░░░░░░░░░░░░░░░░░░░░░░░   177.1 /  1232.3 GiB  14%    │
└──────────────────────────────────────────────────────────────────────────────┘
┌─ Network ────────────────────────────────────────────────────────────────────┐
│ eth0   ↓ 0 B/s        ↑ 0 B/s        total ↓   51.4 GiB  ↑   10.2 GiB        │
│ eth1   ↓ 0 B/s        ↑ 0 B/s        total ↓    0.0 GiB  ↑    0.0 GiB        │
└──────────────────────────────────────────────────────────────────────────────┘





 Refreshes every 2 seconds   q quits
The dashboard: 10 cores and 12 logical processors at 9 % load, 53 °C on the CPU, 36 % of the memory in use, two data volumes, and eth0 and eth1 at 0 B/s, because the sample file does not change between frames.

Download it on the NAS

curl -fsSLO https://kb.nasutils.net/projects/bash/stats.sh

stats.sh Download stats.sh

#!/usr/bin/env bash
# stats.sh: a live dashboard of the NAS. Every 2 seconds it redraws the CPU, its load and temperature, the memory,
# the data volumes and the network rate of each eth port, until you press q.
# Run it: bash stats.sh   (PROC, DF and NOW may point it at sample files and a fixed clock)
set -uo pipefail

PROC=${PROC:-/proc}
A=$'\e[38;5;214m' G=$'\e[32m' R=$'\e[31m' D=$'\e[2m' B=$'\e[1m' N=$'\e[0m' BAR=$'\e[1;30;48;5;214m'
prev_rx=() prev_tx=() prev_us=0

at() { printf '\e[%d;%dH' "$1" "$2"; }

box() { # LINE COLUMN HEIGHT WIDTH TITLE: a frame in amber, empty inside
  local l=$1 c=$2 h=$3 w=$4 i inner
  printf -v inner '%*s' $((w - 2)) ''
  at "$l" "$c" && printf '%s┌%s┐' "$A" "${inner// /─}"
  for ((i = 1; i < h - 1; i++)); do at $((l + i)) "$c" && printf '│%s│' "$inner"; done
  at $((l + h - 1)) "$c" && printf '└%s┘' "${inner// /─}"
  at "$l" $((c + 2)) && printf '%s %s %s' "$B$A" "$5" "$N"
}

bar() { # PERCENT WIDTH: green up to 69 %, amber up to 89 %, red from 90 %
  local p=$1 w=$2 full colour=$G fill rest
  ((p > 100)) && p=100
  ((p >= 70)) && colour=$A
  ((p >= 90)) && colour=$R
  full=$((p * w / 100))
  printf -v fill '%*s' "$full" ''
  printf -v rest '%*s' $((w - full)) ''
  printf '%s%s%s%s%s' "$colour" "${fill// /█}" "$D" "${rest// /░}" "$N"
}

gib() { # KIB: the size in GiB with one decimal
  local t=$((($1 * 10 + 524288) / 1048576))
  printf '%d.%d' $((t / 10)) $((t % 10))
}

rate() { # BYTES_PER_SECOND: the rate in B/s, KiB/s or MiB/s
  if (($1 < 1024)); then
    printf '%d B/s' "$1"
  elif (($1 < 1048576)); then
    printf '%d.%d KiB/s' $(($1 / 1024)) $(($1 % 1024 * 10 / 1024))
  else
    printf '%d.%d MiB/s' $(($1 / 1048576)) $(($1 % 1048576 * 10 / 1048576))
  fi
}

temp() { # WHAT: a getsysinfo temperature ("53 C/127 F") in °C, green, amber from 60, red from 75
  local t colour=$G
  t=$(getsysinfo "$1" 2>/dev/null) || return 1
  t=${t%% C*}
  ((t >= 60)) && colour=$A
  ((t >= 75)) && colour=$R
  printf '%s%s °C%s' "$colour" "$t" "$N"
}

draw_cpu() {
  local name cpus cores l1 l5 l15 load t
  name=$(grep -m1 '^model name' "$PROC/cpuinfo" | sed 's/.*: //; s/(R)//g; s/(TM)//g; s/ CPU//')
  cpus=$(grep -c '^processor' "$PROC/cpuinfo")
  cores=$(awk -F': ' '/^physical id/ {p = $2} /^core id/ {print p "-" $2}' "$PROC/cpuinfo" | sort -u | wc -l)
  read -r l1 l5 l15 _ <"$PROC/loadavg"
  load=$((10#${l1/./} / cpus)) # the load of 1 minute per logical processor, in percent
  box 3 1 8 40 "CPU"
  at 4 3 && printf '%s%.36s%s' "$B" "$name" "$N"
  at 5 3 && printf '%d cores, %d logical processors' "$cores" "$cpus"
  at 6 3 && printf 'Load      %s  %s  %s' "$l1" "$l5" "$l15"
  at 7 3 && bar "$load" 24 && printf ' %3d %%' "$load"
  if t=$(temp cputmp); then at 8 3 && printf 'CPU       %s' "$t"; fi
  if t=$(temp systmp); then at 9 3 && printf 'System    %s' "$t"; fi
}

draw_memory() {
  local key value total=0 avail=0 cache=0 used
  while read -r key value _; do
    case $key in
      MemTotal:) total=$value ;;
      MemAvailable:) avail=$value ;;
      Buffers: | Cached:) cache=$((cache + value)) ;;
    esac
  done <"$PROC/meminfo"
  used=$((total - avail))
  box 3 41 8 40 "Memory"
  at 4 43 && printf 'Total      %6s GiB' "$(gib "$total")"
  at 5 43 && printf 'In use     %6s GiB' "$(gib "$used")"
  at 6 43 && printf 'Available  %s%6s GiB%s' "$G" "$(gib "$avail")" "$N"
  at 7 43 && printf 'Cache      %6s GiB' "$(gib "$cache")"
  at 8 43 && bar $((used * 100 / total)) 24 && printf ' %3d %%' $((used * 100 / total))
}

draw_volumes() { # one row per data volume; sets next, the first line below the box
  local size used pct mnt rows=() row line=12
  while read -r _ size used _ pct mnt; do
    [[ $mnt == /share/* && $mnt != /share/*/* ]] || continue
    rows+=("$(printf '%-16s' "${mnt#/share/}")$(bar "${pct%\%}" 30) $(printf '%7s / %7s GiB %4s' "$(gib "$used")" "$(gib "$size")" "$pct")")
  done < <(if [[ -n ${DF:-} ]]; then cat "$DF"; else df -k; fi)
  ((${#rows[@]})) || rows=("No data volumes under /share.")
  box 11 1 $((${#rows[@]} + 2)) 80 "Volumes"
  for row in "${rows[@]}"; do
    at "$line" 3 && printf '%s' "$row"
    line=$((line + 1))
  done
  next=$((line + 1))
}

draw_network() { # LINE: one row per eth port, the rate since the last frame
  local l=$1 i=0 name rx tx now_us ms rows=() row
  now_us=${EPOCHREALTIME:-}
  now_us=${now_us//[!0-9]/}
  if [[ -n $now_us ]] && ((prev_us > 0)); then ms=$(((now_us - prev_us) / 1000)); else ms=2000; fi
  ((ms > 0)) || ms=1
  while read -r name rx _ _ _ _ _ _ _ tx _; do
    [[ $name == eth* ]] && ((l + ${#rows[@]} < 21)) || continue # the rows that fit above the last line
    [[ -n ${prev_rx[i]:-} ]] || { prev_rx[i]=$rx && prev_tx[i]=$tx; }
    rows+=("$(printf '%-6s ↓ %-12s ↑ %-12s %stotal ↓ %6s GiB  ↑ %6s GiB%s' "${name%:}" \
      "$(rate $(((rx - prev_rx[i]) * 1000 / ms)))" "$(rate $(((tx - prev_tx[i]) * 1000 / ms)))" \
      "$D" "$(gib $((rx / 1024)))" "$(gib $((tx / 1024)))" "$N")")
    prev_rx[i]=$rx prev_tx[i]=$tx i=$((i + 1))
  done < <(sed 's/:/ /' "$PROC/net/dev")
  prev_us=${now_us:-0}
  box "$l" 1 $((${#rows[@]} + 2)) 80 "Network"
  for row in "${rows[@]}"; do
    l=$((l + 1))
    at "$l" 3 && printf '%s' "$row"
  done
}

frame() {
  local model clock next
  model=$(getsysinfo model 2>/dev/null) || model=$(uname -n)
  clock=${NOW:-$(date '+%Y-%m-%d %H:%M:%S')}
  at 1 1 && printf '%s %-20s%-39s%20s%s' "$BAR" "NAS stats" "$model" "$clock" "$N"
  draw_cpu
  draw_memory
  draw_volumes
  draw_network "$next"
  at 24 1 && printf '%s Refreshes every 2 seconds   q quits%s' "$D" "$N"
}

restore() { printf '\e[0m\e[?25h\e[?1049l'; }
trap restore EXIT
trap 'exit 0' INT TERM
printf '\e[?1049h\e[?25l\e[2J'
while true; do
  frame
  IFS= read -rsn1 -t 2 key && [[ $key == q || $key == Q ]] && exit 0
done

What you learn

  • read -rsn1 -t 2 waits for one key for at most 2 seconds, so one loop both refreshes and listens.
  • A rate is the difference of two readings of a counter divided by the time between them.
  • $EPOCHREALTIME gives the time in microseconds, so the script divides by the real interval.
  • sed 's/:/ /' turns the eth0: of /proc/net/dev into a separate word that read can split.
  • Load per logical processor in percent: the load of 1 minute times 100, divided by the logical processors.

How it works

The function frame draws the whole screen: a title bar with the model and the clock, then four boxes. It moves the cursor with \e[LINE;COLUMNH and overwrites the old picture in place, so the screen does not blink between frames. The main loop calls frame and then waits up to 2 seconds for a key. Any key other than q only brings the next frame sooner.

The CPU box shows the name from /proc/cpuinfo, the cores and logical processors, the three load averages and a bar of the load of 1 minute per logical processor. Below them are the CPU and system temperatures from getsysinfo, which turn amber at 60 °C and red at 75 °C. The memory box counts memory in use as MemTotal minus MemAvailable and the cache as Buffers plus Cached.

The network box reads the received and sent bytes of every eth port from /proc/net/dev. It keeps the readings of the last frame in two arrays and divides the difference by the time since that frame. The first frame has nothing to compare with, so it shows 0 B/s. In the test the sample file never changes, so every frame shows 0 B/s. On a NAS the second frame shows the real rate.

Notes to the lines

  • 9The arrays keep the byte counters of the last frame, prev_us its time.
  • 38–46rate chooses B/s, KiB/s or MiB/s and prints one decimal using whole numbers only.
  • 48–55getsysinfo cputmp answers "53 C/127 F"; ${t%% C*} keeps the 53.
  • 59The CPU name without "(R)", "(TM)" and "CPU", so it fits in the box.
  • 63${l1/./} turns "1.17" into "117", which is the load times 100; dividing by 12 logical processors gives 9 %.
  • 91–104The volume box grows with the number of data volumes and tells draw_network where to start.
  • 108–111The interval in milliseconds from $EPOCHREALTIME. QTS's own Bash 3.2 has no such variable, so the script then counts with 2 seconds.
  • 114The first reading of a port becomes its last reading too, so the first rate is 0.
  • 119/proc/net/dev can write eth0:55169935872 without a space; the colon turns into one.
  • 146Wait for a key at most 2 seconds; q ends the loop, and the trap restores the terminal.

Run it

bash stats.sh

The screen refreshes every 2 seconds. Press q to quit.

Try it yourself

Change the 2 in read -rsn1 -t 2 to 5 and watch the rates even out over the longer interval. Add bond* next to eth* in line 113, if your NAS joins its ports into a bond.

More projects in Bash