Skip to content

Instantly share code, notes, and snippets.

@mlgill
Last active October 17, 2022 18:41
Show Gist options
  • Save mlgill/b08b18fc1de2086d9c20 to your computer and use it in GitHub Desktop.
Save mlgill/b08b18fc1de2086d9c20 to your computer and use it in GitHub Desktop.
Bash script to display sorted list of processes using most memory or cpu with colorized output
#!/bin/bash
# Michelle L. Gill
# 2014/10/25
# For use with Today Scripts
# http://www.reddit.com/r/osx/comments/2k24ps/today_scripts_widget_update_colorized_output
# Inspired by: https://gist.github.com/anonymous/470bb40b05173fdb6348
# Set this to "cpu" or "mem"
procname="cpu"
# Number of processes to show
numproc=5
ps -amcwwwxo "pid %$procname command" | while read -r line; ((n++<$((numproc+1)))); do
# Read commands from single line to handle spaces in command name
line=`echo $line | sed -E 's/^ +//g;s/ +/ /g'`
pid=`echo $line | cut -d' ' -f1`
proc=`echo $line | cut -d' ' -f2`
cmd=`echo $line | cut -d' ' -f3-10`
# Setup formatting
fmt=""
# Color formatting for process rows
if (($pid!="PID")); then
# Format numbers
numfmt="%6s %4.1f %s"
# Truncate integer on % memory or cpu to determine color
procint="${proc%%.*}"
if (($procint >= 20)); then
fmt=$'\e[1;31m'
elif (($procint >= 10)); then
fmt=$'\e[33m'
else
fmt=$'\e[m'
fi
else
# Format the header with no color, boldface
fmt=$'\e[1m'
numfmt="%6s %4s %s"
fi
# Print the string
printf "$fmt$numfmt\n" $pid $proc "$cmd"
done
@mlgill
Copy link
Author

mlgill commented Oct 25, 2014

Here is an example of the output in Today Scripts in Yosemite Notification Center:
http://twitter.com/modernscientist/status/526019138750537728/photo/1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment