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.
NAS menu TBS-h574TX ╔═ Menu ═══════════════╗ ║ ║ ║ Memory ║ ║ ▶ Volumes ║ ║ Uptime and load ║ ║ Quit ║ ║ ║ ╚══════════════════════╝ ↑↓ move Enter open q quit
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
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
Download it on the NAS
curl -fsSLO https://kb.nasutils.net/projects/bash/menu.shmenu.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 -rsn1reads one key without Enter and without showing it; an arrow key arrives as three characters.trap restore EXITgives the terminal back its cursor and its normal screen however the script ends.while read -r key valuepicks fields out of/proc/meminfoanddf -kwithout 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
- 7
PROClets 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.
- 12
atmoves the cursor; every other function draws through it. - 14–27
boxdraws the double frame line by line and writes the title over the top edge. - 29–37
barfillsppercent of the width with █ and the rest with dim ░, and picks the colour by the percentage. - 39–42
gibturns KiB into GiB with one decimal using whole numbers only, because Bash has no fractions. - 46–51The loop reads
/proc/meminfoline by line and keeps the two values it needs. - 63–68
df -k(or the file inDF) 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
processorlines. Cores are the distinct pairs ofphysical idandcore 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. - 90
getsysinfo modelis 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;restoreundoes both. - 108–112One key, then up to two more within 0.05 s when the first one was Escape.
Run it
bash menu.shUp 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
- A framed menu in pure BashA Bash script draws a menu in a double frame, moves a highlighted bar with the arrow keys and opens boxes with the NAS's memory, volumes, uptime and load. You learn cursor moves, colours and key reading without any extra tool.
- A greeting at the SSH loginA Bash script greets you by the time of day and shows the NAS model, uptime, CPU, load, the free space of the data volumes and a tip of the day in one framed banner. You learn to frame text with escapes and how to show it at every SSH login on QTS.
- A live dashboard of the NASA Bash script redraws the CPU, load, temperatures, memory, data volumes and network rates of the NAS every 2 seconds until you press q. You learn to wait for a key with a timeout and to compute a rate from two readings of a counter.
- Blink: a memory game with drive-bay LEDsIn this Bash game the four drive-bay LEDs of a drawn NAS light up in a sequence that grows by one each round, and you repeat it with the keys 1 to 4. You learn timed drawing, seeded random numbers and how to ignore keys typed at the wrong moment.
- Copy a folder with a progress barA Bash script copies a folder block by block and shows a progress bar, the bytes copied, the speed and the time left, with an optional speed limit. You learn traps for Ctrl+C, redrawing lines in place and reading keys while a job runs.
- A backup wizard with dialogA Bash script uses dialog to show a checklist of the NAS's share folders, a confirmation, a progress gauge and a summary of what rsync would copy. You learn dialog's boxes, its colour file and how to feed a gauge from a loop.