A Question On Recursion In Ksh

Hi Folks,

I would just like to know how recursion works in ksh or inside a shell in general. I created the following script, but it works(runs recursively) only for 64 times:
----------------
#! /usr/bin/ksh
displaymessage()
{
echo "displaying count: $cnt "
echo "wait for 1 second..."
sleep 1
cnt=$cnt+1
main

}

main()
{
displaymessage
}

#start here
typeset -i cnt=1
main
---------------

The 'main' function calls the 'displaymessage' function, whereas the displaymessage calls 'main' inside it (so is recursive).

The error that i get is: "main: recursion too deep"

Question: How do I make a perfect recursion???

Recursion is allowed (where i work) at a depth of 9 iterations. Basically what your script is doing is:

run main,
---> call message,
---------->run main,
-------------->call message

That is the it re-runs the main command again, it runs itself and thus can never exit, and the functions never exit.

What you need to do is control this using a loop in main, so possibly:

#! /usr/bin/ksh
displaymessage()
{
echo "displaying count: $cnt "
echo "wait for 1 second..."
sleep 1
cnt=$cnt+1

}

main()
{
while true
do
    displaymessage
done
}

#start here
typeset -i cnt=1
main
1 Like