Tuesday, February 15, 2011

Arithmetic expressions with BASH

Lately I needed to write a BASH script that iterates over couple of hosts and counts the total amount of CPU cores.
Since I had many hosts and wanted to see the overall progress of the script (how much percent completed), I had to implement arithmetic expression in my script, let's see how it's done:

I have created a file that stores the array of all my environment hosts , the file is called "servers.txt".
The scripts iterates over that file, and checks the cores on each server via -
"cat /proc/cpuinfo|grep -i proc|wc -l".

If the server is reachable via ping it reads that CPU core data and then simply adds the found cores to total amount of cores and in the end displays the final result.

The problem was to display the percentage of the progress and after scratching my head a bit I came up with this:

echo  "$COUNT*100/$SERVERS_COUNT"|bc -l ;echo -n "Percent done...

We are multiplying our current count ($COUNT) by 100 and dividing the result with the total numbers of server ($SERVER_COUNT), then we pipe the result to command called bc, which does the magic of the calculation.

This is the script, enjoy:

#!/bin/bash
core_count() {
clear
echo "Starting core count, please wait this might take a while..."

SERVERS=`cat servers.txt`
SERVERS_COUNT=`cat servers.txt|wc -l`
TOTAL_CORES=0
COUNT=0

echo "Going to check:$SERVERS_COUNT servers" ;sleep 1
for i in $SERVERS;do
ping -c1 $i &>/dev/null
if [ $? == "0" ];then

CURRENT_CORES=`ssh $i "cat /proc/cpuinfo|grep -i proc|wc -l"`
let TOTAL_CORES+=$CURRENT_CORES
let COUNT+=1
clear
echo  "Working, please be patient..."
echo  "$COUNT*100/$SERVERS_COUNT"|bc -l ;echo -n "Percent done..."

else 
        echo "Server: $i is DOWN, can't determine core number"
fi
done

#############################################
echo -e "\n"
echo "Total cores: $TOTAL_CORES"
}



#Main Program
core_count 2>/dev/null

No comments: