load Prompt

Displaying the current load in the prompt in a colour that varies with the actual load. I couldn't get the colour changing to work within the prompt so an external function is used. Colour changing is thus handled a little differently than usual.

It should be easy to change the load colour sequence to suit your own tastes.

Code:

#!/bin/bash

function load_out() {
  echo -n "$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\).*/\1/" -e "s/ //g")"
}

function load_color() {
  gray=0
  red=1
  green=2
  yellow=3
  blue=4
  magenta=5
  cyan=6
  white=7

  # Colour progression is important ...
  #   bold gray -> bold green -> bold yellow -> bold red -> 
  #   black on red -> bold white on red
  #
  # Then we have to choose the values at which the colours switch, with
  # anything past yellow being pretty important.

  tmp=$(echo $(load_out)*100 | bc)
  let load100=${tmp%.*}

  if [ ${load100} -lt 70 ]
  then
    tput bold ; tput setaf ${gray}
  elif [ ${load100} -ge 70 ] && [ ${load100} -lt 120 ]
  then
    tput bold ; tput setaf ${green}
  elif [ ${load100} -ge 120 ] && [ ${load100} -lt 200 ]
  then
    tput bold ; tput setaf ${yellow}
  elif [ ${load100} -ge 200 ] && [ ${load100} -lt 300 ]
  then
    tput bold ; tput setaf ${red}
  elif [ ${load100} -ge 300 ] && [ ${load100} -lt 500 ]
  then
    tput setaf ${gray} ; tput setab ${red}
  else
    tput bold ; tput setaf ${white} ; tput setab ${red}
  fi
}

function load {
  CYAN="\[$(tput bold ; tput setaf 6)\]"
  NOCOLOUR="\[$(tput sgr0)\]"

  PS1="[\[\$(load_color)\]\$(load_out)${NOCOLOUR}][\D{%H%M}]\
 \u:${CYAN}\w${NOCOLOUR}\$> "
}


http://www.gilesorr.com/bashprompt/prompts/load.html (2.0Kb)
Last modified 20071016 by giles