Skip to content

Instantly share code, notes, and snippets.

@wouterds
Created August 26, 2024 14:57
Show Gist options
  • Save wouterds/c362ba511396caf1e28855314badb188 to your computer and use it in GitHub Desktop.
Save wouterds/c362ba511396caf1e28855314badb188 to your computer and use it in GitHub Desktop.
Get Linux Debian system stats as a json string
#!/bin/bash
# Get used RAM percentage
ram_used=$(free | awk '/Mem:/ {printf "%.2f", $3/$2 * 100}')
# Get average CPU usage percentage
cpu_used=$(top -bn2 -d 0.5 | grep "Cpu(s)" | tail -n 1 | awk '{print $2 + $4}')
# Get used disk space percentage across all disks
disk_used=$(df -h --total | awk '/total/ {print $5}' | sed 's/%//')
# Construct and print JSON string
json_output=$(cat <<EOF
{
"ram_used": ${ram_used},
"cpu_used": ${cpu_used},
"disk_used": ${disk_used}
}
EOF
)
echo "$json_output"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment