OK, I have a little bit of Korn shell script that is exhibiting some VERY weird behavior. I figured out what was happening, so I don't need someone to tell me what's going on. But, I thought it was kind of funny so I thought I'd share it as a little programming puzzle! Here it is.
I have a little test script that loops a number of times. In each loop, it sleeps for several seconds just to slow down the loop. Here's the code...
The expected output is that it will print out "Waiting for 2 seconds", five times, with a delay of two seconds after each, then print "Done!" and exit.
The actual output is very different...
There is nothing in the script that increments the variable SECONDS, but it keeps doubling each time! It takes a total time of 62 seconds (1 minute 2 seconds) to run.
Do you know why?
A hearty attaboy/attagirl (plus a star) to anyone that answers it without peeking at other peoples' answers (use the spoiler tag to hide your answer).
I have a little test script that loops a number of times. In each loop, it sleeps for several seconds just to slow down the loop. Here's the code...
Code:
#!/bin/ksh
SECONDS=2
ITERATIONS=5
while (( ITERATIONS ))
do
print "Waiting for ${SECONDS} seconds"
sleep ${SECONDS}
(( ITERATIONS -= 1 ))
done
print "Done!"
The actual output is very different...
Code:
Waiting for 2 seconds
Waiting for 4 seconds
Waiting for 8 seconds
Waiting for 16 seconds
Waiting for 32 seconds
Done!
Do you know why?
A hearty attaboy/attagirl (plus a star) to anyone that answers it without peeking at other peoples' answers (use the spoiler tag to hide your answer).