MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Shell Bash Scripting: Assignment & Excercise – 3

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.

CommandWhat it showsNotes
date, uptimeCurrent time, time since boot, number of users, 1/5/15-minute load averageA load average that stays above the CPU count (nproc) points to CPU or I/O pressure
wLogged-in users and what each one is runningReads utmp
last -aRecent logins, with the source host in the last columnReads /var/log/wtmp. Some newer distributions use wtmpdb instead, so last may be missing or a different implementation
df -hFilesystem size, used and available spaceUse -P for output that is always one line per filesystem, which is safe to parse
free -mRAM and swap in MiBUse the available column, not free, to judge memory headroom
grep on kernel logOut-of-memory killer eventsThe log location depends on the distribution
top -bCPU summary and processes in batch (non-interactive) modeAlways add -n 1 in scripts
nmap / ss -tlnListening TCP portsss is installed almost everywhere. nmap usually is not
ss -sSocket totals by state and protocolQuick way to spot connection leaks
ps auxfFull process treeCan run to thousands of lines on busy hosts
vmstat 1 5Five one-second samples of CPU, memory, swap and I/OHigh 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.1 is invalid. -p needs a port list, so nmap reads -T4 as 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 | xargs flattens the output into one line, and awk field $17 is then free swap on current procps versions. The field numbers only matched the old free layout that had a -/+ buffers/cache line.
  • The disk line reports the wrong filesystem. After xargs, fields $9 and $11 are the size and available space of whichever filesystem df lists first. That is often devtmpfs or tmpfs, not /.
  • The OOM count is inaccurate. grep -ci kill counts every line that contains "kill" (any process, any signal), not just out-of-memory kills.
  • /var/log/messages often 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 -b without -n never ends on its own. It only stops because head closes the pipe. top -b -n 1 makes 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 pipefail stops the script on an unset variable and makes a pipeline fail when any command in it fails. set -e is left out on purpose: a missing tool should not stop the rest of the report.
  • have() wraps command -v, so optional tools such as last, netstat and journalctl are 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: and Swap: lines by name. It does not count fields across flattened output, so the result is correct even if the column layout changes.
  • journalctl -k -b reads kernel messages from the current boot. Searching for out of memory matches both system-wide and cgroup OOM kills.
  • ps --sort=-%cpu lists the busiest processes reliably. Note that ps reports %CPU as an average over each process's lifetime, not the current instant.

Running and scheduling the report

  1. Save the script as server-health.sh and make it executable with chmod +x server-health.sh.
  2. Check the syntax without running it: bash -n server-health.sh. If it is installed, shellcheck server-health.sh also catches quoting mistakes.
  3. Run it with root privileges so kernel logs and port owners are visible: sudo ./server-health.sh.
  4. Save a dated copy for comparison later, as shown below.
  5. Optionally, install it in /usr/local/bin and 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

ErrorCauseFix
Your port specifications are illegal from nmap-p took -T4 as its port listUse -p-, or better, ss -tln
grep: /var/log/messages: No such file or directoryDebian/Ubuntu or a journald-only systemUse journalctl -k, or the fallback loop in the improved script
No journal files were opened due to insufficient permissionsNon-root user outside the systemd-journal or adm groupRun with sudo, or add the user to one of those groups
last: cannot open /var/log/wtmp or last: command not foundNo wtmp file, or the distribution moved to wtmpdbInstall the package that provides last on your distribution, or skip that section
$'\r': command not foundScript saved with Windows (CRLF) line endingssed -i 's/\r$//' server-health.sh or dos2unix server-health.sh
Permission denied when running ./server-health.shExecute bit not set, or filesystem mounted noexecchmod +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 nproc and warn when the 5-minute load is higher than the core count.
  • Add a --short mode 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Shell Bash Scripting: Assignment & Excercise โ€“ 16

This exercise asks for a Bash script that packs a file or directory into a compressed tar archive and then encrypts it with a passphrase. The solution…

Read More

Shell Bash Scripting: Assignment & Excercise โ€“ 15

This exercise builds a Bash script that takes an IP address, sends it to the free ip-api.com geolocation API with curl, and uses jq to print the…

Read More

Shell script to git add and commit and push each directory at a time

This page shows how to use a Bash script to stage, commit and push changes one directory at a time. That can mean a folder full of…

Read More

AWS Tutorials: AWS CodeBuild – Buildspec code for creating AMI from running instances

This page has an AWS CodeBuild buildspec that finds every running EC2 instance tagged environment=uat and creates an AMI from each one with the AWS CLI. It…

Read More

Shell Bash Scripting: Assignment & Excercise – 7

This exercise uses Bash, rsync and SSH to copy a local file to a remote backup server, then sends an email when the copy finishes. Below the…

Read More

Shell Bash Scripting: Assignment & Excercise – 4

This exercise asks for a Bash script that checks CPU usage and sends an email when it goes over a threshold. The script above reads /proc/stat, but…

Read More
Subscribe
Notify of
guest
2 Comments
Newest
Oldest Most Voted
Suraj Rampure
Suraj Rampure
3 years ago

Sir,
How can we get remote server information, In this programme we can get local server details.

Suraj Rampure
Suraj Rampure
3 years ago

Nice article sir

2
0
Would love your thoughts, please comment.x
()
x