Skip to content

Instantly share code, notes, and snippets.

@zlocate
Created August 9, 2020 21:54
Show Gist options
  • Save zlocate/4175f26a9b99da86641cc5083ff3c70e to your computer and use it in GitHub Desktop.
Save zlocate/4175f26a9b99da86641cc5083ff3c70e to your computer and use it in GitHub Desktop.
#!/bin/bash
# Shell-script that kills top of cpu-usage process (with minimal load limit)
# Dependencies: ps awk bc (available by-default at mostly linux distro)
# Minimal process CPU load after that process will be killed
MIN_CPU_LOAD="50"
echo "Min cpu load to kill $MIN_CPU_LOAD %"
pid=$(ps -eo %cpu,pid,comm --sort -%cpu --no-headers | head -n 1)
# For debugging purposes
# echo $pid
if [[ -n $pid ]]; then
# Maybe use single command to fill array or object-like storage
kcpu=$(echo "$pid" | awk '{print $1}')
kpid=$(echo "$pid" | awk '{print $2}')
command=$(echo "$pid" | awk '{print $3}')
# Workaround to compare float numbers
ift=$(echo "$kcpu"'>'"$MIN_CPU_LOAD" | bc -l)
if [ "$ift" -eq "1" ]; then
echo "Process $command (pid: $kpid) is high cpu usage $kcpu % greater than $MIN_CPU_LOAD. Killing"
kill "$kpid"
else
echo "Process $command (pid: $kpid) is low cpu usage $kcpu %."
fi
else
echo "Does not exist"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment