System and SHELL

Asterisk has 2 ways to run external programs and scripts: System and SHELL.

The System() application will run an external program.  This is very useful for running simple scripts or for using an external program to generate audio.

For example, here’s a simple call logging script written in Ruby:

#!/usr/bin/ruby

call_id=ARGV[0]
time=Time.now.to_s
log_file="/home/ck987/call_log.txt"
# 'a' = append text
file = File.open(log_file, 'a')
file.write("Call from #{call_id} received at #{time}\n")
file.close

If I wanted to run this script in my dialplan I could do something like this:

exten => s,n,System(/home/ck987/ruby/call_log.rb ${CALLERID(num)})

As you can see, we can pass in arguments just like any normal program. System() works with any executable program that’s installed on the Asterisk machine.

The SHELL() function does exactly the same thing as System(), but with one important difference. The SHELL() function will save the output from the external command or program into a variable that can be used later in your dialplan.

For example, here’s a simple ruby script that returns a random number:

#!/usr/bin/ruby
puts rand(10).to_s

I could use this script in my dialplan like this:

exten => s,n,Set(random=${SHELL(/home/ck987/ruby/rnd.rb)})
exten => s,n,SayDigits(${random})

The returned random number is passed into the “random” variable, and then used in the SayDigits() application.

Again, virtually anything that can be run on the command line can be run using System or SHELL.

Here’s an example that will say the number of files in my home directory:

exten => s,n,Set(numfiles=${SHELL(ls -l /home/ck987 | wc -l)})
exten => s,n,SayDigits(${numfiles})