Asterisk AGI sample in bash


This post presents an interesting Asterisk AGI sample script written in Bash. Bash is a great alternative in situations where external scripts need to be executed to implement functionality that Asterisk cannot do. Another option is to use the Lua dialplan. Personally, I use Ruby for the same purpose, either with Adhearsion or AsteriskRuby.

The AGI script is provided below. 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

# The 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 reading those invalid 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