How can i comapre the CPU usage value using shell script, i get a error as [: =: unary operator expected at the line if [ $message -ne "" ]
#!/bin/sh
expected_cpuusage="95"
cpu_usage=`top -n 1 -b|grep Cpu|awk '{print $2}'|cut -d"%" -f1""`
message=""
if [ $cpu_usage -gt $expected_cpuusage ] ##{x%?}
then
echo "CPU usage exceeded";
if [ $message -ne "" ]
then
message="$message\n\nCPU usage exceeded configured usage limit \nCurrent CPU usage is $cpu_usage\nConfigured CPU usage is $expected_cpuusage";
else
message="CPU usage exceeded configured usage limit \nCurrent CPU usage is $cpu_usage\nConfigured CPU usage is $expected_cpuusage";
fi ;
fi
>is a redirection operator. You want-gtThis requires that $cpu_usage look like an integer and will fail and generate an error if it does not. (ie, if it contains characters other than 0-9. -gt does not compare floating point values, so strings that contain ‘.’ will not work.) For floating point comparisons, use expr:
There are slicker ways to do this comparison using bash builtins like [[, but these constructs limit the portability of the script.
The other error you are seeing occurs when you use an empty string. Try using quotes:
but it is much clearer to use: