Write me a bash script that gets the current cpu usage, memory usage, and uptime of the…
- User
Write me a bash script that gets the current cpu usage, memory usage, and uptime of the system
- Assistant
Below is a simple Bash script that retrieves the current CPU usage, memory usage, and system uptime. This script uses common Linux utilities such as
top,awk,free, anduptimeto gather the necessary information.#!/bin/bash # Get CPU usage # Using top command with batch mode to get the CPU usage. The awk command extracts the usage percentage. CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}') # Get Memory Usage # Using free command to get memory usage statistics, then awk to parse the desired values and calculate the percentage. MEM_USAGE=$(free | grep Mem | awk '{print $3/$2 * 100.0"%"}') # Get System Uptime # Uptime command gives the system uptime directly. UPTIME=$(uptime -p) # Output the information echo "CPU Usage: $CPU_USAGE" echo "Memory Usage: $MEM_USAGE" echo "System Uptime: $UPTIME"Here's a breakdown of what each part does:
-
CPU Usage: The script uses
topwith-bn1options to run in batch mode and only one iteration to get the system's current CPU usage. It then parses the output usinggrepto find the line containing CPU usage information, which is then processed withawkandsedto extract and calculate the percentage of CPU usage. -
Memory Usage: It utilizes
freeto get the memory statistics, thengrepto find the line starting with "Mem". Withawk, it calculates the percentage of used memory by dividing the used memory ($3) by the total memory ($2) and multiplying by 100. -
System Uptime: The
uptime -pcommand gives a human-readable output of how long the system has been running.
How to Use the Script
- Copy the script into a file, for example,
system_stats.sh. - Give it execution permission with the command:
chmod +x system_stats.sh. - Run the script:
./system_stats.sh.
Please note, this script is designed for Linux systems and might require adjustments or different commands for other Unix-like systems such as FreeBSD or macOS.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.