Thursday, April 10, 2008

Number Padded With Zeros

While my colleague is doing the documentation, I am pretty free at this moment and therefore I can blog a bit.

In my previous blog, I mentioned that I am currently working on a 48-node grid cluster. The servers' naming convention is like "servername" followed by 2 digit number ranging from 01 to 48. The previous vendor created a bash shell to start daemon on all the nodes and it looked like this:

for ((i=1;i<10;++i))
do
 ssh root@servername0$i /usr/local/bin/some-daemon
done

for ((i=10;i<48;++i))
do
 ssh root@servername$i /usr/local/bin/some-daemon
done

As you can see, the above code just repeat itself. It is pretty easy to ensure the number are padded with zero and the final script does not have to repeat itself again.

for ((i=1;i<48;++i))
do
 i2=`echo $i | awk '{printf("%02d",$1)}'`
 ssh root@servername$i2 /usr/local/bin/some-daemon
done

If you are fan of Bourne shell, you can do like this. Also, I introduced a new function seq that automatically pad the number with zero

seq()
{
awk 'END{for(i='$1';i<='$2';++i){printf("%02d ",i)}}' /dev/null
}
for i2 in `seq 1 48`
do
 ssh root@servername$i2 /usr/local/bin/some-daemon
done

The seq function basically take advantage of the shell so that I the first and second arguments to the function concatenates to the entire awk code. If you were to break it down, it is something like this:

  • awk 'END{for(i='
  • $1
  • ';i<='
  • $2
  • ';++i){printf("%02d ",i)}}' /dev/null
Those in red will be interrupted by the shell before they are passed to the awk. Make sure you do not include any space in between.

Labels:

0 Comments:

Post a Comment

<< Home