I’m trying to work through a script to email me a notification if the load is too high on our server. I found a good one but it’s giving me and error when I run it, and I can’t see why.
Running the code below gives the error:
line 13: syntax error near unexpected token `fi’
I thought I had to laid out correctly though. Thanks!
#!/bin/bash THR=10 MAIL="address@domain.com" VAR=`uptime|awk -F, '{print $4}'|awk '{print $3}'` OUT=`echo "$VAR $THR" | awk '{if ($1 > $2) print "yes"; else print "no"}'` if [ "$VAR" == "" ] then # it's within the first 24 hours of uptime VAR=`uptime|awk -F, '{print $3}'|awk '{print $3}'` OUT=`echo "$VAR $THR" | awk '{if ($1 > $2) print "yes"; else print "no"}'` fi if [ "$OUT" == "yes" ] then echo "The current load $VAR is greater than the threshold $THR" | mail $MAIL -s "Server Load Alert" echo "Alert generated because $VAR is greater than $THR" else echo "No alert as $VAR > $THR" fi echo "load = $VAR"
Advertisement
Answer
Sorry, no offence, but your bash style is terrible!
Here’s a better version:
#!/bin/bash thr=10 mail="address@domain.com" read var _ < /proc/loadavg if (( $(bc -l <<< "$var>$thr") )); then echo "The current load $var is greater than the threshold $thr" | mail "$mail" -s "Server Load Alert" echo "Alert generated because $var is greater than $thr" else echo "No alert as $var <= $thr" fi echo "load = $var"
The changes are the following:
- Use lower case variable names, as upper case variable names are considered bad bash practice.
- Don’t parse the output of the command
uptime
using millions of pipes, subshells andawk
s because it’s inefficient, the same information is obtained directly from the file/proc/loadavg
, with aread
builtin. - Don’t use
awk
to test for inequalities, usebc
, it’s more efficient (and you don’t need a variable$OUT
at all). - No backticks! Use the
$(...)
construct instead (easier to read, to nest, and better bash practice).
I haven’t tested the script, just corrected yours as I read it. Please tell me if it works for you.