Build a Menu-Driven Linux Administration Toolkit
Administrators run the same handful of commands again and again: how full are the disks, which process uses the memory, who can log in, which ports are open, is a service running, what do the last lines of a log say. This project collects those reports in one script, toolkit.sh, that can be used in two ways. Started without arguments, it shows a numbered menu for people. Started with an action name, it runs that one report and exits with a meaningful status, so cron jobs and other scripts can use it too.
The project combines the menu techniques of lessons 86 and 134, functions (lesson 88 to 94), reading files line by line (lesson 114), argument parsing with getopts (lesson 130) and the safe habits from the security lessons (154 to 161). Every report is read-only: the toolkit never changes the system, which makes it safe to hand to a junior administrator.
What the Script Should Do
- Show a menu with
selectand run the chosen report. - Offer the same reports as command-line actions:
toolkit.sh disk,toolkit.sh top 3, and so on. - Validate every argument before it is used, and print a clear message when it is wrong.
- Return status 0 when a report is fine, 1 when it found or hit a problem, and 2 for a usage error.
- Optionally write an audit line (time, user, action) to a file with
-l.
Design Decisions
Every Report Is a Function with a Clear Contract
Each report is one function named act_NAME. It prints its output and returns 0 when everything is fine or 1 when there is a problem. The disk report, for example, returns 1 when a file system is more than 80% full, so a cron job can run toolkit.sh disk || mail ... without parsing any text. Because the menu and the command line call the same functions, a report only has to be written and tested once.
A single function, run_action, is the only place that turns an action name into a function call:
run_action() {
local action=$1; shift
local status=0
case $action in
system) act_system ;;
disk) act_disk ;;
top) act_top "$@" ;;
service) act_service "$@" ;;
...
*) return 2 ;;
esac || status=$?
audit "$action $*"
return "$status"
}
The names of the actions are fixed words in a case statement. User input is never used to build a command or a function name, which would be a command injection risk (lesson 155). An unknown action returns 2 and the caller turns it into a usage error. The construct esac || status=$? records the exit status of the function that ran without stopping the script, and the audit line is written afterwards in every case.
The Menu with select
select (lesson 86) prints the items as a numbered list, shows the prompt stored in PS3, reads a line and stores it in two variables: REPLY holds what the user typed, and the chosen variable holds the matching item or stays empty for an invalid number. The script uses $REPLY in the case statement, so the numbers stay in one place and the order of the items can change without a second edit:
select choice in "${items[@]}"; do
case $REPLY in
1) run_action system ;;
2) run_action disk ;;
3) read -r -p "How many processes [5]: " arg1; run_action top "${arg1:-5}" ;;
...
9) echo "Goodbye."; return 0 ;;
*) echo "Please enter a number from 1 to ${#items[@]}." ;;
esac
break
done || return 0
Two details make the menu pleasant. First, select normally repeats forever without redrawing the list. The break after the case leaves the select after one action, and the surrounding while true loop starts a new select, which prints the menu again. Second, when the input ends (the user presses Ctrl-D), select finishes with a non-zero status, and || return 0 leaves the function normally instead of looping endlessly.
Questions are asked with read -r -p, and ${arg1:-5} supplies the default when the user just presses Enter (lesson 45).
Validating Input
Every action that takes an argument checks it first. Two small helpers and a regular expression cover the cases:
is_number() { [[ ${1:-} =~ ^[1-9][0-9]*$ ]]; }
The expression accepts only a whole number of at least 1, so abc, 0, -3 and 2; rm x are all rejected. The service name is checked with ^[A-Za-z0-9@._-]+$, which is the set of characters systemd names use. A name such as a;b fails the test and never reaches systemctl. Files and directories are checked with -f and -d before they are used, and always passed after -- or in quotes (lesson 161).
Reading the System Without Fragile Parsing
Several reports use the kernel's own files, because their format is stable:
- The system report reads
/etc/os-releasewithIFS='=' read -r key valueand picks the linePRETTY_NAME. The${value//\"/}expansion removes the quotation marks. The load comes from/proc/loadavg. - The users report reads
/etc/passwdwithIFS=: read -r name pass uid gid gecos home shell. An account can log in only when its shell is a real shell, so lines that end innologinorfalseare skipped with acasepattern. - The ports report reads
/proc/net/tcpand/proc/net/tcp6. Each line holds the local address as hexadecimal text such as0100007F:1F9B, and the socket state in another column, where0Ameans LISTEN. The part after the colon is the port in hexadecimal, and the arithmetic expression$((16#$hexport))converts it to decimal. The ports are stored as keys of an associative array (lesson 102), which removes duplicates (a server that listens on IPv4 and IPv6 appears twice), andsort -nprints them in numeric order. This way the report works even on a minimal system where thessandnetstatprograms are not installed.
Output That Does Not Break Under pipefail
The script runs with set -uo pipefail, so a pipeline fails if any part of it fails. A command such as sort -rn | head -n 5 can fail this way: when head has printed five lines it exits, sort receives a "broken pipe" signal and the pipeline reports status 141, although nothing is wrong. The script therefore uses sed -n '1,5p' where it limits output. sed reads all of its input, so nothing is cut off early, and the status stays 0. The option -e is intentionally not set: the toolkit prints reports and decides about each status itself (lesson 119).
The Audit Log
An administration tool should leave a trace. With -l FILE, every action appends one line:
audit() {
[[ -n $logfile ]] || return 0
printf '%s %s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "${SUDO_USER:-$(id -un)}" "$*" >> "$logfile"
}
SUDO_USER is set by sudo to the name of the person who started it, so the log shows the real person and not just root. The script uses id -un as the fallback, because the variable USER is not set in every environment, and with set -u an unset variable would stop the script (this was found while testing).
The Complete Script
#!/usr/bin/env bash
#
# toolkit.sh - a menu-driven Linux administration toolkit (read-only reports)
#
# Usage: toolkit.sh [-l LOGFILE] [ACTION [ARGUMENT]]
#
# Without an ACTION the script shows an interactive menu.
# With an ACTION it runs that one report and exits (useful for cron and scripts).
#
# Actions:
# system host name, kernel, uptime, load and memory
# disk file system usage, warning above 80%
# top [N] the N processes that use the most memory (default 5)
# users accounts that can log in, and who is logged in now
# ports TCP ports that are listening
# service NAME state of a systemd service
# log FILE [N] the last N lines of a log file (default 10)
# find-large DIR the 5 largest files below DIR
#
# Options:
# -l LOGFILE append a line to LOGFILE for every action that is run
# -h show this help
#
# Exit status: 0 success, 1 the action reported a problem, 2 usage error.
set -uo pipefail
export LC_ALL=C
readonly PROG=${0##*/}
usage() { sed -n '3,26s/^# \{0,1\}//p' "$0"; }
die() { printf '%s: %s\n' "$PROG" "$1" >&2; exit 2; }
logfile=
while getopts ':l:h' opt; do
case $opt in
l) logfile=$OPTARG ;;
h) usage; exit 0 ;;
:) die "option -$OPTARG needs a value" ;;
*) die "unknown option -$OPTARG (try -h)" ;;
esac
done
shift $((OPTIND - 1))
# --- helpers --------------------------------------------------------------------
title() { printf '\n== %s ==\n' "$1"; }
audit() { # audit ACTION [ARGUMENT] - remember what was run
[[ -n $logfile ]] || return 0
printf '%s %s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "${SUDO_USER:-$(id -un)}" "$*" >> "$logfile"
}
is_number() { [[ ${1:-} =~ ^[1-9][0-9]*$ ]]; }
# --- actions: each prints a report and returns 0 (fine) or 1 (problem) -----------
act_system() {
title "System"
local pretty=unknown line
if [[ -r /etc/os-release ]]; then
while IFS='=' read -r key value; do
[[ $key == PRETTY_NAME ]] && pretty=${value//\"/}
done < /etc/os-release
fi
printf '%-10s %s\n' "Host:" "$(hostname)"
printf '%-10s %s\n' "System:" "$pretty"
printf '%-10s %s\n' "Kernel:" "$(uname -r)"
printf '%-10s %s\n' "Uptime:" "$(uptime -p 2>/dev/null || echo unknown)"
read -r l1 l5 l15 _ < /proc/loadavg
printf '%-10s %s %s %s (%s CPU core(s))\n' "Load:" "$l1" "$l5" "$l15" "$(nproc)"
free -h | sed -n '1,2p'
return 0
}
act_disk() {
title "Disk usage"
local problem=0 fs size used avail pct mount
printf '%-24s %6s %6s %6s %5s\n' Mount Size Used Avail Use%
while read -r fs size used avail pct mount; do
printf '%-24s %6s %6s %6s %5s' "$mount" "$size" "$used" "$avail" "$pct"
if (( ${pct%\%} > 80 )); then printf ' <-- above 80%%'; problem=1; fi
printf '\n'
done < <(df -h -P -x tmpfs -x devtmpfs -x overlay 2>/dev/null | tail -n +2)
return "$problem"
}
act_top() {
local n=${1:-5}
is_number "$n" || { echo "top: '$n' is not a positive number"; return 1; }
title "Top $n processes by memory"
ps -eo pid,user:12,%mem,%cpu,comm --sort=-%mem | sed -n "1,$((n + 1))p"
}
act_users() {
title "Accounts that can log in"
local name pass uid gid gecos home shell
while IFS=: read -r name pass uid gid gecos home shell; do
case $shell in
*/nologin|*/false|"") continue ;;
esac
printf '%-14s uid=%-6s shell=%s\n' "$name" "$uid" "$shell"
done < /etc/passwd
title "Logged in now"
if [[ -n $(who) ]]; then who; else echo "(nobody)"; fi
}
act_ports() {
title "Listening TCP ports"
local file hexport state found=0
local -A seen=()
# /proc/net/tcp and tcp6 list every TCP socket; state 0A means LISTEN
for file in /proc/net/tcp /proc/net/tcp6; do
[[ -r $file ]] || continue
while read -r _ local_addr _ state _; do
[[ $state == 0A ]] || continue
hexport=${local_addr##*:}
seen[$((16#$hexport))]=1
done < <(tail -n +2 "$file")
done
local port
for port in $(printf '%s\n' "${!seen[@]}" | sort -n); do
printf 'port %s\n' "$port"; found=1
done
(( found )) || echo "(no listening TCP ports)"
}
act_service() {
local name=${1:-}
[[ $name =~ ^[A-Za-z0-9@._-]+$ ]] || { echo "service: give a valid service name"; return 1; }
title "Service $name"
if ! command -v systemctl > /dev/null || [[ ! -d /run/systemd/system ]]; then
echo "systemd is not running on this machine"; return 1
fi
local state
state=$(systemctl is-active "$name" 2>/dev/null || true)
printf 'State: %s\n' "${state:-unknown}"
[[ $state == active ]]
}
act_log() {
local file=${1:-} n=${2:-10}
[[ -n $file ]] || { echo "log: give a file name"; return 1; }
[[ -f $file && -r $file ]] || { echo "log: cannot read $file"; return 1; }
is_number "$n" || { echo "log: '$n' is not a positive number"; return 1; }
title "Last $n lines of $file"
tail -n "$n" -- "$file"
}
act_find_large() {
local dir=${1:-}
[[ -d $dir ]] || { echo "find-large: not a directory: ${dir:-<none>}"; return 1; }
title "Largest files below $dir"
find "$dir" -xdev -type f -printf '%s\t%p\n' 2>/dev/null | sort -rn | sed -n '1,5p' |
while IFS=$'\t' read -r bytes path; do
printf '%10s %s\n' "$(numfmt --to=iec "$bytes")" "$path"
done
}
# run one action by name; unknown names are a usage error
run_action() {
local action=$1; shift
local status=0
case $action in
system) act_system ;;
disk) act_disk ;;
top) act_top "$@" ;;
users) act_users ;;
ports) act_ports ;;
service) act_service "$@" ;;
log) act_log "$@" ;;
find-large) act_find_large "$@" ;;
*) return 2 ;;
esac || status=$?
audit "$action $*"
return "$status"
}
# --- interactive menu -----------------------------------------------------------
menu() {
local choice arg1 arg2
local -a items=("System summary" "Disk usage" "Top memory users" "Login accounts"
"Listening ports" "Service state" "View a log file"
"Find large files" "Quit")
PS3=$'\nChoose a number: '
while true; do
title "Linux administration toolkit"
select choice in "${items[@]}"; do
case $REPLY in
1) run_action system ;;
2) run_action disk ;;
3) read -r -p "How many processes [5]: " arg1; run_action top "${arg1:-5}" ;;
4) run_action users ;;
5) run_action ports ;;
6) read -r -p "Service name: " arg1; run_action service "$arg1" ;;
7) read -r -p "Log file: " arg1; read -r -p "Lines [10]: " arg2
run_action log "$arg1" "${arg2:-10}" ;;
8) read -r -p "Directory: " arg1; run_action find-large "$arg1" ;;
9) echo "Goodbye."; return 0 ;;
*) echo "Please enter a number from 1 to ${#items[@]}." ;;
esac
break # redraw the menu after every action
done || return 0 # end of input (Ctrl-D) leaves the menu
done
}
# --- main -----------------------------------------------------------------------
if (( $# == 0 )); then
menu
else
run_action "$@"
status=$?
(( status == 2 )) && die "unknown action '$1' (try -h)"
exit "$status"
fi
Using the Toolkit from the Command Line
The System Report
$ ./toolkit.sh system
== System ==
Host: vm
System: Ubuntu 24.04.5 LTS
Kernel: 6.18.44-fc-v1098
Uptime: up 2 minutes
Load: 0.16 0.04 0.01 (2 CPU core(s))
total used free shared buff/cache available
Mem: 7.8Gi 507Mi 7.3Gi 13Mi 272Mi 7.3Gi
The three load values are the averages of the last 1, 5 and 15 minutes. Comparing them with the number of cores (here 2) shows whether the machine is busy: a value near the core count means every core is fully used.
The Disk Report and Its Exit Status
$ ./toolkit.sh disk; echo "status $?"
== Disk usage ==
Mount Size Used Avail Use%
/ 252G 13G 30G 29%
/opt/claude-code 433M 396M 29M 94% <-- above 80%
/opt/env-runner 49M 32M 16M 68%
/mnt/attach/outputs 1.0P 0 1.0P 0%
status 1
One file system is above the limit, so the line is marked and the status is 1. The options -x tmpfs -x devtmpfs -x overlay leave out virtual file systems that would only add noise, and df -P prints the portable format with one line per file system, which is safe to split with read.
Top Memory Users, Ports and Logs
$ ./toolkit.sh top 2
== Top 2 processes by memory ==
PID USER %MEM %CPU COMMAND
85 root 4.0 2.8 claude
210 root 0.5 0.0 environment-man
$ ./toolkit.sh ports
== Listening TCP ports ==
port 2024
port 8123
port 39327
port 41295
$ ./toolkit.sh -l audit.log log t.log 2
== Last 2 lines of t.log ==
c
d
$ cat audit.log
2026-12-02 20:37:59 root log t.log 2
The port list above was produced while a test web server was listening on port 8123. The audit file contains one line per action: the time, the person and the action with its arguments.
The Largest Files
$ ./toolkit.sh find-large /usr/bin
== Largest files below /usr/bin ==
190M /usr/bin/pandoc
108M /usr/bin/dockerd
46M /usr/bin/docker
43M /usr/bin/containerd
28M /usr/bin/x86_64-linux-gnu-lto-dump-13
find -printf '%s\t%p\n' prints the size in bytes and the path separated by a tab, which sorts correctly as a number with sort -rn. numfmt --to=iec converts the byte count into a readable form such as 190M. The option -xdev keeps find on one file system.
Reports That Depend on the System
Some reports need tools that are not present everywhere. The toolkit says so and returns 1, instead of printing a confusing error. On the test machine, where systemd is not running:
$ ./toolkit.sh service ssh; echo "status $?"
== Service ssh ==
systemd is not running on this machine
status 1
On a server that uses systemd, the same command prints State: active and returns 0 for a running service, and prints the real state (inactive, failed) and returns 1 otherwise. This part could not be tested against a real systemd here, because the test machine does not run it.
Input Errors
$ ./toolkit.sh top abc
top: 'abc' is not a positive number (status 1)
$ ./toolkit.sh log nofile
log: cannot read nofile (status 1)
$ ./toolkit.sh find-large /nonexist
find-large: not a directory: /nonexist (status 1)
$ ./toolkit.sh service 'a;b'
service: give a valid service name (status 1)
$ ./toolkit.sh bogus
toolkit.sh: unknown action 'bogus' (try -h) (status 2)
Using the Interactive Menu
Without arguments, the script shows the menu. A short session in which the user chooses the disk report (2) and then quits (9) looks like this:
$ ./toolkit.sh
== Linux administration toolkit ==
1) System summary 4) Login accounts 7) View a log file
2) Disk usage 5) Listening ports 8) Find large files
3) Top memory users 6) Service state 9) Quit
Choose a number: 2
== Disk usage ==
Mount Size Used Avail Use%
/ 252G 13G 30G 29%
...
== Linux administration toolkit ==
1) System summary 4) Login accounts 7) View a log file
...
Choose a number: 9
Goodbye.
Entering a number outside the range prints Please enter a number from 1 to 9. and shows the menu again. Pressing Ctrl-D ends the program cleanly with status 0. The same toolkit can be placed in /usr/local/bin and given to a team as the one command to remember.
Ideas for Extending the Project
- A submenu. Add a second level for user tasks (list, lock, unlock) and ask for confirmation before any change, as in lesson 160.
- Color. Print the warning markers in red with
tput setaf 1when the output goes to a terminal ([[ -t 1 ]]). - A report mode. Add an action
allthat runs every report in turn and writes the result to a dated file, then schedule it with cron (lesson 170). - Plug-ins. Source extra
act_*functions from a directory (lesson 95) so that each team can add reports without editing the main script. - Remote use. Run the toolkit on several servers with
ssh server /usr/local/bin/toolkit.sh diskand combine the exit statuses (lesson 179).