Friday, May 2, 2008

Counting Numbers in Shell Scripts

Scripts are very useful especially in automating repetitive task for system administration. Let me share to you a very simple shell script that will display numbers from 1 to 10 using while loop.

#!/bin/sh
# Filename: count.sh
# Description: Display numbers 1 to 10 using while loop
# Author: Obispo

# initialize a variable
i=1

# do the loop
while [ ${i} -le 10 ]
do
# you may place your repetitive task here
echo "count: ${i}"
i=`expr ${i} + 1`
done

exit 0


Output:
# ./count.sh
count: 1
count: 2
count: 3
count: 4
count: 5
count: 6
count: 7
count: 8
count: 9
count: 10


You're probably wondering whats the use of printing numbers 1 to 10 in the screen? I know how to that even when my eyes are closed. Well, all I can say is that you will need it someday when you grow up. :)


No comments: