0

I am outputting the HDD temps of my system to a text file on a local webserver that I can check every once in a while to monitor hdd temps when the system is under load. I was wondering if there is a way I can highlight if the temp is over a certain number. Here is a sample of the output I am getting (I'm piping it through column to arrange the columns nicely):

hddtemp -w /dev/sdg /dev/sdh /dev/sdi /dev/sda /dev/sdb | column -t -s ":"

/dev/sdg   ST4000NM0033-9ZM170       46°C
/dev/sdh   ST4000NM0033-9ZM170       44°C
/dev/sdi   Hitachi HUA723030ALA641   43°C
/dev/sda   ST4000NM0033-9ZM170       43°C
/dev/sdb   Hitachi HUA723030ALA641   44°C

On the right where it shows the temp, I would like to make it red if it's over 50c. I am assuming there's a way to do it with grep, I'm just not sure if that's the only (or best) way to do it. And I'm not sure how to handle the '"dregee"C' part of it.

Sabat
  • 1

1 Answers1

0

Take the below shell function, a modification of the one from my other answer. This one will detect strings that start with a space or a tab, end with an ASCII digit+°C, where in the middle there is 5, 6, 7, 8 or 9, or more than one ASCII digit (to cover cases where the temperature raises above 99°C). In each such string the part after the leading space or tab will be highlighted.

This is the function:

highlight() (
if [ -t 1 ] || [ "$1" = -f ]; then
   start="$(tput bold)"
   end="$(tput sgr0)"
   sed -E "s#([[:blank:]])(([56789]|[0123456789]{2,})[0123456789]°C)#\\1$start\\2$end#g;"
else
   cat
fi
)

It's a filter. Use it in a pipe, e.g.:

hddtemp … | column … | highlight

Notes:

  • Regular expressions work with strings and characters, not with numbers. In general it's not a trivial task to translate an arbitrary numeric range to a pattern. Here I managed to do it in a relatively simple way, but note 50°C will be highlighted. Excluding 50 while including 51 and above would complicate the pattern.
  • I deliberately used [0123456789] (not e.g. [[:digit:]]) to match only these characters, regardless of what your locale is.
  • tput bold and such are not portable. Adjust start= and end= to your needs.
  • Inside the sed code # is used as a delimiter for s. It's crucial not to have # from the expansion of $start or $end. Adjust to your needs. Remember s in sed can use almost any character as delimiter.
  • The filter tests if its stdout is a terminal. If not, it becomes cat (i.e. a no-op filter). You can force highlighting even to a non-terminal with highlight -f.