LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   shell (bash) scripting - strings vs. integers (http://www.linuxquestions.org/questions/linux-newbie-8/shell-bash-scripting-strings-vs-integers-498071/)

bullfrog1870 11-02-2006 07:18 PM

shell (bash) scripting - strings vs. integers
 
Using FC5 with /bin/bash

I'm trying to figure out how to get the CPU load average as an integer so my script can take further action if greater than x%.

I wanted to use "uptime | cut -d, -f4". However, I can't use the -gt operator since it requires an integer and the above mentioned command returns a string.

Can I convert string to integer somehow?

Thanks...

////// 11-02-2006 07:44 PM

Code:

uptime |awk '{print $10}' |sed -e 's/,//g'
Output:
2.30

Edit:

I used this one:

Code:

TEST=$(uptime |awk '{print $10}' |sed -e 's/,//g')

if [[ "$TEST" > "0.80" ]]; then
echo "load over 0.80"
else
echo "load under 0.80"
fi


chort 11-02-2006 08:00 PM

My stab at it (there must be a more elegant way to do this):

Code:

#!/usr/local/bin/bash

foo=`uptime | cut -d ',' -f4 | tr -d '.' | tr -d [:blank:] | sed -e s/^0+//`

if [ $((foo)) -gt 100 ]
then
        echo "Load over 1.00"
else
        echo "Load under 1.01"
fi

BTW I suppose this could use an explanation. Suppose you got 0.06 for the load average. Here is what it would look like after each step above (cut, tr, tr, sed):
Code:

0.06
 006
006
6

The reason you need to strip the leading 0s is because bash will assume it's octal if it starts with a 0. The $(()) around foo forces arithmatic comparison.

unSpawn 11-02-2006 08:51 PM

How about (Bash):
Code:

chkavg() { lim=30; avg=(`uptime`); avg=${avg[8]//,/}; return $(bc -l <<< "$avg>$lim"); }
Uptime gives a space separated string so we can use an array w/o needing to muck with the IFS, pick the nineth element and strip off the comma, do a here bc thingie (couldn't make $(()) work) and return the result since that's all that is necessary for further ops.


All times are GMT -5. The time now is 04:42 PM.