NASutils Knowledge BaseUnofficialPolski

Bash · projectA framed menu in pure Bash

This script gives your NAS a small menu in the SSH window: a highlighted bar, arrow keys, and boxes with memory, volumes, uptime and load. It needs only Bash and the files in /proc, so the same technique works for any menu you want to build.

Programming on the NAS › Bash in 30 lessons

 NAS menu                                                             TBS-h574TX


   ╔═ Menu ═══════════════╗
   ║                      ║
   ║    Memory            ║
   ║  ▶ Volumes           ║
   ║    Uptime and load   ║
   ║    Quit              ║
   ║                      ║
   ╚══════════════════════╝












 ↑↓ move   Enter open   q quit
The menu with the bar on Volumes and the NAS model in the title bar.
 NAS menu                                                             TBS-h574TX


   ╔═ Menu ═══════════════╗
   ║                      ║
   ║    Memory            ║    ╔═ Volumes ══════════════════════════════════╗
   ║  ▶ Volumes           ║    ║                                            ║
   ║    Uptime and load   ║    ║  CACHEDEV1_DATA  281.8 GiB of 1327.1 GiB   ║
   ║    Quit              ║    ║  ██████░░░░░░░░░░░░░░░░░░░░░░░░ 21%        ║
   ║                      ║    ║  CACHEDEV2_DATA  177.1 GiB of 1232.3 GiB   ║
   ╚══════════════════════╝    ║  ████░░░░░░░░░░░░░░░░░░░░░░░░░░ 14%        ║
                               ║                                            ║
                               ╚════════════════════════════════════════════╝










 Any key closes the box
The Volumes box: two data volumes, each with its used space and a green bar.
 NAS menu                                                             TBS-h574TX


   ╔═ Menu ═══════════════╗
   ║                      ║
   ║    Memory            ║    ╔═ Uptime and load ══════════════════════════╗
   ║    Volumes           ║    ║                                            ║
   ║  ▶ Uptime and load   ║    ║  Up for     1 d 13 h 10 min                ║
   ║    Quit              ║    ║  Load       1.17 / 0.90 / 0.88             ║
   ║                      ║    ║             1, 5 and 15 minutes            ║
   ╚══════════════════════╝    ║  Cores      10                             ║
                               ║  Processors 12 logical                     ║
                               ║                                            ║
                               ╚════════════════════════════════════════════╝









 Any key closes the box
The Uptime and load box: 1 d 13 h 10 min, the three load averages, 10 cores and 12 logical processors.

Download it on the NAS

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

menu.sh Download menu.sh

#!/usr/bin/env bash
# menu.sh: a framed menu in pure Bash. The arrow keys move the bar, Enter opens a box with the NAS's memory,
# its volumes or its uptime and load, any key closes the box, q quits.
# Run it: bash menu.sh   (PROC and DF may point it at sample files instead of /proc and df -k)
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'
items=("Memory" "Volumes" "Uptime and load" "Quit")
sel=0

at() { printf '\e[%d;%dH' "$1" "$2"; } # LINE COLUMN: move the cursor

box() { # LINE COLUMN HEIGHT WIDTH TITLE: a double 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 >= 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 GiB' $((t / 10)) $((t % 10))
}

show_memory() {
  local key value total=0 avail=0 used
  while read -r key value _; do
    case $key in
      MemTotal:) total=$value ;;
      MemAvailable:) avail=$value ;;
    esac
  done <"$PROC/meminfo"
  used=$((total - avail))
  box 6 32 7 46 "Memory"
  at 8 35 && printf 'Total      %s' "$(gib "$total")"
  at 9 35 && printf 'In use     %s' "$(gib "$used")"
  at 10 35 && printf 'Available  %s%s%s' "$G" "$(gib "$avail")" "$N"
  at 11 35 && bar $((used * 100 / total)) 30 && printf ' %d %%' $((used * 100 / total))
}

show_volumes() {
  local fs size used _a pct mnt line=8
  box 6 32 8 46 "Volumes"
  while read -r fs size used _a pct mnt; do
    [[ $mnt == /share/* && $mnt != /share/*/* ]] || continue
    at "$line" 35 && printf '%s%-15s%s %s of %s' "$B" "${mnt#/share/}" "$N" "$(gib "$used")" "$(gib "$size")"
    at $((line + 1)) 35 && bar "${pct%\%}" 30 && printf ' %s' "$pct"
    line=$((line + 2))
  done < <(if [[ -n ${DF:-} ]]; then cat "$DF"; else df -k; fi)
  ((line == 8)) && at 8 35 && printf 'No data volumes under /share.'
}

show_uptime() {
  local up l1 l5 l15 cpus cores
  read -r up _ <"$PROC/uptime"
  read -r l1 l5 l15 _ <"$PROC/loadavg"
  cpus=$(grep -c '^processor' "$PROC/cpuinfo")
  cores=$(awk -F': ' '/^physical id/ {p = $2} /^core id/ {print p "-" $2}' "$PROC/cpuinfo" | sort -u | wc -l)
  up=${up%.*}
  box 6 32 9 46 "Uptime and load"
  at 8 35 && printf 'Up for     %s%d d %d h %d min%s' "$B" $((up / 86400)) $((up % 86400 / 3600)) $((up % 3600 / 60)) "$N"
  at 9 35 && printf 'Load       %s / %s / %s' "$l1" "$l5" "$l15"
  at 10 35 && printf '%s           1, 5 and 15 minutes%s' "$D" "$N"
  at 11 35 && printf 'Cores      %d' "$cores"
  at 12 35 && printf 'Processors %d logical' "$cpus"
}

draw() { # the whole screen: title, menu, keys
  printf '\e[2J'
  local model
  model=$(getsysinfo model 2>/dev/null) || model=$(uname -n)
  at 1 1 && printf '%s %-58s%21s%s' "$BAR" "NAS menu" "$model" "$N"
  box 4 4 $((${#items[@]} + 4)) 24 "Menu"
  local i
  for i in "${!items[@]}"; do
    at $((6 + i)) 6
    if ((i == sel)); then printf '%s ▶ %-17s%s' "$BAR" "${items[i]}" "$N"; else printf '   %-17s' "${items[i]}"; fi
  done
  at 24 1 && printf '%s ↑↓ move   Enter open   q quit%s' "$D" "$N"
}

restore() { printf '\e[0m\e[?25h\e[?1049l'; }
trap restore EXIT
trap 'exit 0' INT TERM
printf '\e[?1049h\e[?25l' # a screen of its own, no cursor

draw
while true; do
  IFS= read -rsn1 key
  if [[ $key == $'\e' ]]; then
    IFS= read -rsn2 -t 0.05 rest
    key=$key$rest
  fi
  case $key in
    $'\e[A' | $'\eOA') sel=$(((sel + ${#items[@]} - 1) % ${#items[@]})) ;;
    $'\e[B' | $'\eOB') sel=$(((sel + 1) % ${#items[@]})) ;;
    q | Q) exit 0 ;;
    '')
      case $sel in
        0) show_memory ;;
        1) show_volumes ;;
        2) show_uptime ;;
        3) exit 0 ;;
      esac
      at 24 1 && printf '\e[2K%s Any key closes the box%s' "$D" "$N"
      IFS= read -rsn1 _
      ;;
  esac
  draw
done

What you learn

  • printf '\e[%d;%dH' moves the cursor to a line and a column, so the script can draw anywhere on the screen.
  • ${inner// /═} turns a row of spaces into a row of frame characters, which makes a box of any width.
  • read -rsn1 reads one key without Enter and without showing it; an arrow key arrives as three characters.
  • trap restore EXIT gives the terminal back its cursor and its normal screen however the script ends.
  • while read -r key value picks fields out of /proc/meminfo and df -k without awk.

How it works

The script keeps the menu entries in an array and the number of the highlighted entry in sel. The function draw clears the screen and paints the title bar, the framed menu and the key help on the last line. The highlighted entry gets black letters on an amber background.

The main loop reads one key. An arrow key starts with the Escape character, so the script reads two more characters and compares the whole sequence with \e[A (up) and \e[B (down). Enter arrives as an empty string. It calls the function of the entry, which draws a second box beside the menu. The next key closes the box and the menu comes back.

The boxes read the NAS directly. Memory in use is MemTotal minus MemAvailable from /proc/meminfo. The volumes are the lines of df -k mounted directly under /share, each with a bar that turns amber at 70 % and red at 90 %. Uptime comes from /proc/uptime in seconds and the load from /proc/loadavg. The counts of cores and logical processors come from /proc/cpuinfo.

Notes to the lines

  • 7PROC lets the test point the script at sample files; on the NAS it stays /proc.
  • 8Each colour is an ANSI escape kept in a short variable: amber is colour 214 of the 256-colour palette.
  • 12at moves the cursor; every other function draws through it.
  • 14–27box draws the double frame line by line and writes the title over the top edge.
  • 29–37bar fills p percent of the width with █ and the rest with dim ░, and picks the colour by the percentage.
  • 39–42gib turns KiB into GiB with one decimal using whole numbers only, because Bash has no fractions.
  • 46–51The loop reads /proc/meminfo line by line and keeps the two values it needs.
  • 63–68df -k (or the file in DF) goes into the loop through < <(...); only mounts one level under /share count, such as /share/CACHEDEV1_DATA. Container Station and Samba mount more folders deeper inside, and the test skips them.
  • 76–77Logical processors are the processor lines. Cores are the distinct pairs of physical id and core id: this chip has 10 cores and 12 logical processors, because only some of its cores run two threads.
  • 78${up%.*} cuts the fraction off the seconds, so Bash can divide them into days, hours and minutes.
  • 90getsysinfo model is QNAP's own command; on a PC it is missing and the host name takes its place.
  • 101–104The script switches to a screen of its own (\e[?1049h) and hides the cursor; restore undoes both.
  • 108–112One key, then up to two more within 0.05 s when the first one was Escape.

Run it

bash menu.sh

Up and Down move the bar, Enter opens the box of the entry, any key closes it, and q or the entry Quit ends the script.

Try it yourself

Add an entry "Date and time" to the array before Quit, a function that shows date in a box, and a line for it in case $sel (Quit then moves to number 4). Change the 30 in the calls of bar to 20 and see the bars shrink inside the same frame.

More projects in Bash