Your questions imply that you don’t understand the AGI protocol yet.
Specifically, you should read the AGI environment from STDIN first. Next, for EACH request you issue to Asterisk on STDOUT, you need to read the response from STDIN. Failing to do this breaks the protocol and will result in ‘unexpected behavior.’
The protocol is simple, but subtle. Nobody gets it right the first time. I suggest you use an existing library in a language like C, Perl, PHP, etc. where you have access to debugging facilities.
This is not to denigrate shell as a programming language. Some of my best friends use shell – but not for AGIs.
I wrote an AGI in FORTRAN just to prove a point, but I suggest that you should choose a tool more appropriate to the task.