The script above prints a quick health report for a Linux server: uptime, logged-in users, recent logins, disk and memory use, OOM killer events, the busiest processes, open ports, socket statistics and vmstat. Several lines in it are broken or give wrong numbers on current distributions. This page explains each command, fixes the bugs and gives an improved script you can run, schedule and extend.
Write a Shell Bash Script for report server related information
What each part of the script reports
The exercise asks you to collect the information an engineer checks first when someone says a server is slow or misbehaving. Every line in the gist calls a standard Linux tool. Knowing what each one shows makes the report easier to read and easier to fix when a tool behaves differently on another distribution.
| Command | What it shows | Notes |
|---|---|---|
date, uptime | Current time, time since boot, number of users, 1/5/15-minute load average | A load average that stays above the CPU count (nproc) points to CPU or I/O pressure |
w | Logged-in users and what each one is running | Reads utmp |
last -a | Recent logins, with the source host in the last column | Reads /var/log/wtmp. Some newer distributions use wtmpdb instead, so last may be missing or a different implementation |
df -h | Filesystem size, used and available space | Use -P for output that is always one line per filesystem, which is safe to parse |
free -m | RAM and swap in MiB | Use the available column, not free, to judge memory headroom |
grep on kernel log | Out-of-memory killer events | The log location depends on the distribution |
top -b | CPU summary and processes in batch (non-interactive) mode | Always add -n 1 in scripts |
nmap / ss -tln | Listening TCP ports | ss is installed almost everywhere. nmap usually is not |
ss -s | Socket totals by state and protocol | Quick way to spot connection leaks |
ps auxf | Full process tree | Can run to thousands of lines on busy hosts |
vmstat 1 5 | Five one-second samples of CPU, memory, swap and I/O | High wa means I/O wait. Non-zero si/so means active swapping |
Problems in the original script
The script runs, but some sections print errors or misleading numbers:
nmap -p -T4 127.0.0.1is invalid.-pneeds a port list, so nmap reads-T4as the port list and exits with an illegal port specification error. The author probably meant-p-(all ports). nmap is also not installed by default on most servers, and scanning 127.0.0.1 misses services that listen only on a specific external IP.- The memory line reports the wrong value.
free -m | xargsflattens the output into one line, and awk field$17is then free swap on current procps versions. The field numbers only matched the oldfreelayout that had a-/+ buffers/cacheline. - The disk line reports the wrong filesystem. After
xargs, fields$9and$11are the size and available space of whichever filesystemdflists first. That is oftendevtmpfsortmpfs, not/. - The OOM count is inaccurate.
grep -ci killcounts every line that contains "kill" (any process, any signal), not just out-of-memory kills. /var/log/messagesoften does not exist. Debian and Ubuntu write to/var/log/syslog, and systems that only use journald have neither file. Reading the file also usually requires root.top -bwithout-nnever ends on its own. It only stops becauseheadcloses the pipe.top -b -n 1makes one pass and exits cleanly.
Corrected and improved script
This version keeps the same report structure. It fixes the parsing bugs, uses journalctl for OOM events with a fallback to the classic log files, replaces nmap with ss, and checks that optional tools exist before calling them.
#!/usr/bin/env bash
# server-health.sh - quick health report for a Linux server
# Usage: sudo ./server-health.sh (works without sudo, with less detail)
set -uo pipefail
section() {
printf '\n==================== %s ====================\n' "$1"
}
have() {
command -v "$1" >/dev/null 2>&1
}
if [ "$(id -u)" -ne 0 ]; then
echo "Note: not running as root; kernel logs and port owners may be hidden." >&2
fi
section "Host"
echo "Hostname : $(uname -n)"
echo "Date : $(date '+%Y-%m-%d %H:%M:%S %Z')"
echo "Kernel : $(uname -r)"
if [ -r /etc/os-release ]; then
echo "OS : $(. /etc/os-release && echo "${PRETTY_NAME:-unknown}")"
fi
section "Uptime and load average"
uptime
section "Currently connected users"
w
section "Last 3 logins"
if have last; then
last -a -n 3 2>/dev/null || echo "No login records available"
else
echo "'last' is not installed"
fi
section "Disk usage"
df -hP / | awk 'NR==2 {printf "Free/total on /: %s / %s (%s used)\n", $4, $2, $5}'
echo
df -h -x tmpfs -x devtmpfs -x squashfs
section "Memory"
free -m | awk '
/^Mem:/ {printf "Available/total memory: %s / %s MB\n", $7, $2}
/^Swap:/ {printf "Free/total swap: %s / %s MB\n", $4, $2}'
section "OOM killer events"
if have journalctl; then
oom=$(journalctl -k -b --no-pager 2>/dev/null | grep -ci 'out of memory')
echo "OOM events since last boot: $oom"
else
logfile=""
for f in /var/log/messages /var/log/syslog /var/log/kern.log; do
if [ -r "$f" ]; then logfile=$f; break; fi
done
if [ -n "$logfile" ]; then
start_log=$(head -1 "$logfile" | cut -c 1-15)
oom=$(grep -ci 'out of memory' "$logfile")
echo "OOM events in $logfile since $start_log: $oom"
else
echo "No readable kernel log found"
fi
fi
section "CPU summary"
top -b -n 1 | head -5
section "Top 5 processes by CPU"
ps -eo pid,user,%cpu,%mem,etime,comm --sort=-%cpu | head -6
section "Top 5 processes by memory"
ps -eo pid,user,%cpu,%mem,rss,comm --sort=-%mem | head -6
section "Listening TCP ports"
if have ss; then
ss -tlnp
elif have netstat; then
netstat -tlnp
else
echo "Neither ss nor netstat is installed"
fi
section "Socket summary"
ss -s 2>/dev/null || echo "ss not available"
section "Process tree (first 40 lines)"
ps auxf --width=200 | head -40
section "vmstat (5 samples, 1 second apart)"
vmstat 1 5Code language: PHP (php)
set -uo pipefailstops the script on an unset variable and makes a pipeline fail when any command in it fails.set -eis left out on purpose: a missing tool should not stop the rest of the report.have()wrapscommand -v, so optional tools such aslast,netstatandjournalctlare skipped cleanly when they are not installed.df -hP /gives exactly one data line for the root filesystem. awk then reads columns$2(size),$4(available) and$5(use%).- awk matches the
Mem:andSwap:lines by name. It does not count fields across flattened output, so the result is correct even if the column layout changes. journalctl -k -breads kernel messages from the current boot. Searching forout of memorymatches both system-wide and cgroup OOM kills.ps --sort=-%cpulists the busiest processes reliably. Note thatpsreports %CPU as an average over each process's lifetime, not the current instant.
Running and scheduling the report
- Save the script as
server-health.shand make it executable withchmod +x server-health.sh. - Check the syntax without running it:
bash -n server-health.sh. If it is installed,shellcheck server-health.shalso catches quoting mistakes. - Run it with root privileges so kernel logs and port owners are visible:
sudo ./server-health.sh. - Save a dated copy for comparison later, as shown below.
- Optionally, install it in
/usr/local/binand schedule it with cron.
# Save a dated report
sudo ./server-health.sh | tee "health-$(uname -n)-$(date +%F).txt"
# Run against a remote host without copying the file there
ssh admin@web01 'sudo bash -s' < server-health.sh
# Daily report at 07:00 (add with: sudo crontab -e)
0 7 * * * /usr/local/bin/server-health.sh > /var/log/server-health.log 2>&1Code language: PHP (php)
Note: With ssh ... 'sudo bash -s', sudo must not prompt for a password, because the script is read from stdin. Use a sudoers rule limited to this one command, or connect as a user that already has the needed access.
Example output
Values differ on every host. Here is an abbreviated run on a small VM:
==================== Host ====================
Hostname : web01
Date : 2026-11-21 09:14:02 UTC
Kernel : 6.8.0-87-generic
OS : Ubuntu 24.04 LTS
==================== Uptime and load average ====================
09:14:02 up 12 days, 3:41, 1 user, load average: 0.21, 0.30, 0.27
==================== Disk usage ====================
Free/total on /: 31G / 49G (35% used)
==================== Memory ====================
Available/total memory: 2874 / 3913 MB
Free/total swap: 2047 / 2047 MB
==================== OOM killer events ====================
OOM events since last boot: 0
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
Your port specifications are illegal from nmap | -p took -T4 as its port list | Use -p-, or better, ss -tln |
grep: /var/log/messages: No such file or directory | Debian/Ubuntu or a journald-only system | Use journalctl -k, or the fallback loop in the improved script |
No journal files were opened due to insufficient permissions | Non-root user outside the systemd-journal or adm group | Run with sudo, or add the user to one of those groups |
last: cannot open /var/log/wtmp or last: command not found | No wtmp file, or the distribution moved to wtmpdb | Install the package that provides last on your distribution, or skip that section |
$'\r': command not found | Script saved with Windows (CRLF) line endings | sed -i 's/\r$//' server-health.sh or dos2unix server-health.sh |
Permission denied when running ./server-health.sh | Execute bit not set, or filesystem mounted noexec | chmod +x server-health.sh, or run bash server-health.sh |
Extend the exercise
A report only helps if someone reads it. A useful next step is to add thresholds and an exit code, so cron or a monitoring agent can react when a limit is crossed:
status=0
disk_pct=$(df -P / | awk 'NR==2 {gsub("%","",$5); print $5}')
if [ "$disk_pct" -ge 90 ]; then
echo "WARNING: / is ${disk_pct}% full"
status=1
fi
mem_avail_pct=$(free | awk '/^Mem:/ {printf "%d", $7*100/$2}')
if [ "$mem_avail_pct" -le 10 ]; then
echo "WARNING: only ${mem_avail_pct}% memory available"
status=1
fi
exit "$status"Code language: PHP (php)
- Accept thresholds as arguments with
getopts, for example-d 85 -m 15. - Compare the load average with
nprocand warn when the 5-minute load is higher than the core count. - Add a
--shortmode that prints only the summary lines and leaves out the process tree and vmstat. - Print selected values as JSON so another tool can collect them.
Frequently asked questions
Why should a server health script run with sudo?
Kernel logs, the journal for other users and the process owning each listening port are visible only to root or to members of groups such as adm or systemd-journal. Without sudo the script still runs, but those sections come back empty or incomplete.
How do I check for OOM killer events on Ubuntu?
Run sudo journalctl -k | grep -i 'out of memory' for kernel messages, or search /var/log/syslog or /var/log/kern.log. Ubuntu does not use /var/log/messages by default.
Which column of free shows how much memory is really left?
Use the available column. It estimates how much memory new applications can use without swapping, because it counts page cache that can be reclaimed. The free column leaves that cache out, so it looks misleadingly low on a healthy server.
Why use ss instead of nmap to list open ports?
ss -tln reads the kernel's socket table directly, is installed on nearly every distribution, and lists listeners on every address. nmap scans from the outside, often is not installed, and against 127.0.0.1 it only finds services bound to loopback or all interfaces.
How can I run the same health script on many servers?
Loop over hostnames and stream the script over SSH, for example for h in web01 web02; do ssh "$h" 'bash -s' < server-health.sh > "$h.txt"; done. For larger fleets, a configuration management tool such as Ansible handles this better.
Related tutorials
- Linux Commands and Shell Scripting Reference for Linux Admins and DevOps Engineers
- What is Bash and use cases of Bash?
- Shell and Bash Interview Questions: Practical Answers, Commands, and Script Patterns
- More Shell Scripting tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals
Sir,
How can we get remote server information, In this programme we can get local server details.
Nice article sir