Asterisk AGI sample in bash


Asterisk AGI sample in bash, which is very interesting. Bash is a great alternative in situations where external scripts need to be executed to implement functionality that Asterisk cannot do. Another option is using Lua dialplan. Personally, I use Ruby for the same purpose, either with [Adhearsion](http://adhearsion.com or AsteriskRuby.

Anyway, here is the AGI script. It is very basic, but fully functional:

#!/bin/bash 
declare -a array 
while read -e ARG && [ "$ARG" ] ; do 
        array=(` echo $ARG | sed -e 's/://'`) 
        export ${array[0]}=${array[1]} 
done 

# following variables are available from asterisk 
echo $agi_request >&2 
echo $agi_channel >&2 
echo $agi_language >&2 
echo $agi_type >&2 
echo $agi_uniqueid >&2 
echo $agi_callerid >&2 
echo $agi_dnid >&2 
echo $agi_rdnis >&2 
echo $agi_context >&2 
echo $agi_extension >&2 
echo $agi_priority >&2 
echo $agi_enhanced >&2 

checkresults() { 
        while read line 
        do 
        case ${line:0:4} in 
        "200 " ) echo $line >&2 
                 return;; 
        "510 " ) echo $line >&2 
                 return;; 
        "520 " ) echo $line >&2 
                 return;; 
        *      ) echo $line >&2;; #keep on reading those Invlid command 
                                  #command syntax until "520 End ..." 
        esac 
        done 
} 

res=<SOME SCRIPT> 

echo "1.  Setting Variable 'Test Variable' ..." >&2 
echo "SET VARIABLE TestVariable \"$res\"" 
checkresults 

echo "=================== Complete ====================" >&2