Operations 3 min read

How ChatGPT Generates a Simple Shell Script to Monitor Linux Systems

This article presents a concise 10‑line Bash script, generated by ChatGPT, that gathers key Linux system metrics such as CPU, memory, disk usage, load average, network connections, log size, uptime, logged‑in users, process count, and current time.

Advanced AI Application Practice
Advanced AI Application Practice
Advanced AI Application Practice
How ChatGPT Generates a Simple Shell Script to Monitor Linux Systems

A Zhihu question prompted the creation of a short Bash script for Linux system monitoring, and the author tried code generated by ChatGPT.

The resulting script consists of ten commands, each prefixed with an English comment describing the metric being collected. It uses standard utilities like top, free, df, uptime, netstat, du, who, and ps to retrieve the following information:

#!/bin/bash
# Check CPU usage
cpu_usage=$(top -b -n1 | grep "Cpu(s)" | awk '{print $2}')
echo "CPU usage: $cpu_usage"
# Check memory usage
mem_usage=$(free -m | awk 'NR==2{printf "%.2f%%
", $3*100/$2}')
echo "Memory usage: $mem_usage"
# Check disk usage
disk_usage=$(df -h | awk '$NF=="/"{printf "%s
", $5}')
echo "Disk usage: $disk_usage"
# Check system load
load_average=$(uptime | awk '{print $10}' | sed 's/,$//')
echo "System load: $load_average"
# Check network connections count
connection_count=$(netstat -ant | grep ESTABLISHED | wc -l)
echo "Network connections: $connection_count"
# Check log directory size
log_size=$(du -sh /var/log | awk '{print $1}')
echo "Log size: $log_size"
# Check system uptime
uptime=$(uptime | awk '{print $3,$4}' | sed 's/,//')
echo "System uptime: $uptime"
# Check current logged-in users count
user_count=$(who | wc -l)
echo "Logged-in users: $user_count"
# Check total process count
process_count=$(ps -A --no-headers | wc -l)
echo "Process count: $process_count"
# Check current system time
system_time=$(date)
echo "System time: $system_time"

The script prints each metric with a clear label, making it easy to read the output directly in the terminal.

Accompanying screenshots illustrate the script’s execution and the resulting metric values.

Author: Bigder<br/>Date: 2023‑03‑09

ChatGPTbashshell scriptsystem metricsLinux monitoring
Advanced AI Application Practice
Written by

Advanced AI Application Practice

Advanced AI Application Practice

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.