Sunday, December 23, 2007

Recursive Bash Program


< source_code>
#!/bin/bash
LIMIT=$1
if [ $2 ]
then
CELL=$2
else
CELL=[] 
fi 
#******************
print_horizontal_line()
{
ME=0
while [ $ME -lt $LIMIT ] 
do
echo -n $CELL 
let "ME= ME+1"
done
}
#******************

#******************
print_vertical_line()
{
ME2=0
while [ $ME2 -lt $LIMIT ] 
do
print_horizontal_line  
echo     
let "ME2= ME2+1"
done
}
#******************
print_vertical_line;
let "LIMIT= LIMIT/2"
if [ $LIMIT -le 0 ]
then
exit
else
$0 $LIMIT $CELL
fi
exit
</source_code>

This short program to the above serves to demonstrate some basic bash programming syntax and a (very) basic use of recursion. If the program is run on the command line as:

lancemiller$ recursive_bash 4
[][][][]
[][][][]
[][][][]
[][][][]
[][]
[][]
[]
In shell programming the arguments are numbered
$0  $1   $2   $3   $4 ....etc 
recursive_bash 4
 ^             ^
 |             |
$0             $1

The recursive_bash program is going to take $1 (numeral 4 in this example) and perform some math and print a certain amount of characters as a result. First $1 is assigned to the variable LIMIT. Math and print statements occur using $LIMIT. $CELL is the character that will be printed. Argument $2 is optional. Example:

lancemiller$ recursive_bash 4 cat
catcatcatcat                   ^
catcatcatcat                   |
catcatcatcat              arg $2   
catcatcatcat
catcat
catcat
cat

$LIMIT is divided by 2.-> let "LIMIT= LIMIT/2" Then the recursive moment comes in recursive_bash at the line that says: 
$0 $LIMIT $CELL
$0 is the program itself(recursive_bash). It is called over and over till
let "LIMIT= LIMIT/2" results in zero. When $LIMIT is equal or less than zero the program exits.

No comments: