1

I'm trying to create a simple script that checks if the CPU Usage is at a certain level. I have a Raspberry Pi for this project.

The only issue I have currently is that I have the variable CPU which is the CPU usage, when the script runs, I get the error

line 25: [: 4.8: integer expression expected

I'm not sure why bash returns this if BASH really doesn't care about int, String, etc. like JAVA does. Found that out here.

Also, I have the if statement: if $CPU -gt 1 only for testing (it's supposed to return true right now)

red='\e[0;31m'
yellow='\e[1;33m'
NC='\e[0m' # No Color
echo -e "${NC}Starting Server!${NC}"
echo -e "${red}Errors in red!${NC}"
echo -e "${yellow}Info in yellow!${NC}"
sleep 1
echo -e "\n\n"
##CPU USAGE STUFF
echo -e "${yellow}Current CPU Usage:"
CPU=$(top -bn1 | grep "Cpu(s)" | \
           sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \
           awk '{print 100 - $1""}')
echo $CPU %
echo -e "${NC}**********${NC}"
cd /root/mc_server/
sleep 1


##CPU USAGE LOOP CHECKER
while :
do
        sleep 5
        echo $CPU
        if [ $CPU -gt 1 ]
        then
        echo -e "${red}ALERT! CPU Usage is TOO HIGH!${red}"
        fi

done
##


##java -Xmx400M -jar bukkit.jar -o true
4
  • integer means integer. If you pass bash a value like 4.8 then it starts wondering if it needs to look for an exponent value, ie. 4.800889e27, and that would be a lot of work ;-). Just round your 4.8 value or truncate it and then you'll have an integer value that will work. case $CPU in *\.* ) CPU=${CPU%%.*} ;; esac might help. Good luck. Commented Sep 1, 2014 at 19:55
  • @shellter thanks, I'll go ahead and try it Commented Sep 1, 2014 at 19:56
  • @Olivr3000 as shelter says, simply take the whole-number from $CPU. The most efficient way is to remove everything up to and including the decimal beginning at the right with substring extraction. CPU=${CPU%.*} %% works, the only difference being it say remove all occurrences of . beginning at the right, compared to % which is first occurrence. Commented Sep 1, 2014 at 20:12
  • @shellter Yeah, you're both right :) Commented Sep 1, 2014 at 20:13

1 Answer 1

4

The issue is that 4.8 is an non-integer value.

You can use bc to deal with non-integer values like so:

if [[ $(echo "$CPU > 1" | bc -l) -eq 1 ]];

it will return boolean expressions as either 1 for true or 0 for false.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.