0

Getting syntax error for below shell script. Unable to figure out where the problem lies. Please help me guys. Thanks in Advance.

Code:

#!/bin/bash

# Check if package sensors (for Ubuntu) is installed, if not install it
dpkg -l | grep -i sensors > /dev/null

if [ "$?" == "0" ]; then
  echo "Package sensors already installed on system. Analyzing temperature!"
else
  sudo apt-get install sensors && echo "Package sensors now installed"
fi

# Set threshold temperature
threshold="+80.0°C"

# Check if temp has reached threshold, trigger mail
tempnow=$(sensors | sed -n '20p' | awk '{print $NF}')

res=`echo "$tempnow $threshold" | awk '{ if($1 > $2) print "Exceeds"; else print "Normal" }'`

if [ "$res" == "Exceeds" ]
then
  echo "Temperature exceeds threshold. Triggering mail to system owners..."
  mail -s "CPU temperature too high on system" [email protected]
elif [ "$res" == "Normal" ]
  echo "Temperature under limit. Ignoring countermeasures!"
else
  echo "Unable to determine value"
fi

Output:

Package sensors already installed on system. Analyzing temperature!
/home/luckee/scripts/cputemp.sh: line 26: syntax error near unexpected token `else'
/home/luckee/scripts/cputemp.sh: line 26: `else'

2 Answers 2

2

In Line 24:

24    elif [ "$res" == "Normal" ] 
25    then           # <------ Missing in your original code
26      echo "Temperature under limit. Ignoring countermeasures!"

Use shellcheck.net, for debugging such trivial issues.

1

You need an extra then after your elif line :)

#!/bin/bash

# Check if package sensors (for Ubuntu) is installed, if not install it
dpkg -l | grep -i sensors > /dev/null

if [ "$?" == "0" ]; then
  echo "Package sensors already installed on system. Analyzing temperature!"
else
  sudo apt-get install sensors && echo "Package sensors now installed"
fi

# Set threshold temperature
threshold="+80.0°C"

# Check if temp has reached threshold, trigger mail
tempnow=$(sensors | sed -n '20p' | awk '{print $NF}')

res=`echo "$tempnow $threshold" | awk '{ if($1 > $2) print "Exceeds"; else print "Normal" }'`

if [ "$res" == "Exceeds" ]
then
  echo "Temperature exceeds threshold. Triggering mail to system owners..."
  mail -s "CPU temperature too high on system" [email protected]
elif [ "$res" == "Normal" ]
then  # <== HERE!
  echo "Temperature under limit. Ignoring countermeasures!"
else
  echo "Unable to determine value"
fi

Not the answer you're looking for? Browse other questions tagged or ask your own question.