Super Technologies

!Using Variables in Asterisk Dialplans
Asterisk can make use of global and channel-specific variables for arguments to commands. Variables are referenced in the dialplan (extensions.conf) using the syntax

${foo}

where ”foo” is the name of the variable. A variable name may be any alphanumeric string beginning with a letter. User-defined variable names are not case sensitive — ${FOO} and ${Foo} refer to the same variable — but Asterisk-defined variables ”are” case-sensitive — ${EXTEN} works, but ${exten} doesn’t.

There are three types of variables: global variables, channel variables, and environment variables.
*__Global__ variables can be set either in the ~np~[globals]~/np~ category of ((Asterisk config extensions.conf|extensions.conf)) or by using the ((Asterisk cmd SetGlobalVar|SetGlobalVar)) command. Once defined, they can be referenced by any channel at any time.
*__Channel__ variables are set using the ((Asterisk cmd Set|Set)) command (previously “setvar”). Each ((Asterisk channels|channel)) gets its own variable space, so there is no chance of collisions between different calls, and the variable is automatically trashed when the channel is hungup.
* __Environment__ variables provide a means to access unix environment variables from within Asterisk. There’s a list further down this page.
If you define a channel variable with the same name as a global variable (and remember: user-defined variable names are not case sensitive), references to that variable name will return the value of the channel variable. For example, let us say that you define a context “FooTest” with a single extension, 100, with the following definition:(:smile:)

~np~[FooTest]~/np~
exten => 100,1,SetGlobalVar(FOO=5)
exten => 100,2,NoOp(${FOO})
exten => 100,3,NoOp(${foo})
exten => 100,4,SetVar(foo=8)
exten => 100,5,NoOp(${FOO})
exten => 100,6,NoOp(${foo})

(Note the use of the ((Asterisk cmd NoOp|NoOp)) command to assist in debugging.) If you dial extension 100 in context FooTest, and you have Asterisk running with a verbose console, you will see output similar to the following:

— Executing SetGlobalVar(“Zap/1-1”, “FOO=5”) in new stack
— Setting global variable ‘FOO’ to ‘5’
— Executing NoOp(“Zap/1-1”, “5”) in new stack
— Executing NoOp(“Zap/1-1”, “5”) in new stack
— Executing SetVar(“Zap/1-1”, “foo=8”) in new stack
— Executing NoOp(“Zap/1-1”, “8”) in new stack
— Executing NoOp(“Zap/1-1”, “8”) in new stack

We discover that after the call to SetGlobalVar, ${FOO} and ${foo} returned the value of the global variable, giving the value 5. After the call to SetVar, the global variable “foo” was obscured by the channel variable “foo”; ${FOO} and ${foo} both gave the value 8. The value of the global variable remains unchanged at 5, however, and any other channels that refer to the global variable ${foo} would still get the value 5.

!Inheritance of Channel Variables
Prepending a single _ character to a variables name in SetVar will cause that variable to be inherited by channels created by the main channel. eg. when using Dial(Local/…); once inherited these variables will not be further inherited. Prepending two _ characters will cause them to be inherited indefinitely.

Note that for retrieval purposes these variable names do not include the underscores.

~np~[TestInherit]~/np~
exten => 100,1,SetVar(~np~__~/np~FOO=5)
exten => 100,2,Dial(Local/test@CheckInherit)
exten => test,1,NoOp(${FOO})

will result in FOO being inherited. Without the underscores, the new local channel would start with a clean slate.

!!Example

exten => 104,1,SetVar(FEE=fee)
exten => 104,2,SetVar(_FIE=fie)
exten => 104,3,SetVar(__FUM=fum)
exten => 104,4,Dial(Local/105)

exten => 105,1,NoOp(${FEE})
exten => 105,2,NoOp(${FIE})
exten => 105,3,NoOp(${FUM})
exten => 105,4,Dial(Local/106)

exten => 106,1,NoOp(${FEE})
exten => 106,2,NoOp(${FIE})
exten => 106,3,NoOp(${FUM})

results in

— Executing SetVar(“SIP/oberon-365e”, “FEE=fee”) in new stack
— Executing SetVar(“SIP/oberon-365e”, “_FIE=fie”) in new stack
— Executing SetVar(“SIP/oberon-365e”, “__FUM=fum”) in new stack
— Executing Dial(“SIP/oberon-365e”, “Local/105”) in new stack
— Called 105
— Executing NoOp(“Local/105@default-7263,2”, “”) in new stack
— Executing NoOp(“Local/105@default-7263,2”, “fie”) in new stack
— Executing NoOp(“Local/105@default-7263,2”, “fum”) in new stack
— Executing Dial(“Local/105@default-7263,2”, “Local/106”) in new stack
— Called 106
— Executing NoOp(“Local/106@default-49be,2”, “”) in new stack
— Executing NoOp(“Local/106@default-49be,2”, “”) in new stack
— Executing NoOp(“Local/106@default-49be,2”, “fum”) in new stack

(This did not work correctly prior to the 1.2 release.)

!Predefined Channel Variables
There are some channel variables set by Asterisk that you can refer to in your dialplan definitions. Asterisk-defined variables, in contrast to user-defined variables, are case sensitive. __Note__: Several of these builtin variables have been converted to functions in 1.2, to allow setting their values.
*__${ACCOUNTCODE}__: Account code, if specified – see ((Asterisk billing))
*__${ANSWEREDTIME}__: Time when the call was answered.
*__${BLINDTRANSFER}__: The active SIP channel that dialed the number. This will return the SIP Channel that dialed the number when doing blind transfers – see ((BLINDTRANSFER))
*__${CALLERID}__: The current Caller ID (name and number)
*__${CALLERIDNAME}__: The current Caller ID name
*__${CALLERIDNUM}__: The current Caller ID number (Note that this is not necessarily numeric as the name would indicate and can legitimately contain the space character. Commands acting on this variable (such as ‘GotoIf’, for example) should be aware of this).
* THE ABOVE ARE DEPRECATED in at least 1.2.0, and do not work correctly. USE THE FOLLOWING INSTEAD ${CALLERID(num)} ${CALLERID(name)}
*__${CALLINGPRES}__: PRI Call ID Presentation variable for incoming calls (See ((Asterisk cmd callingpres|callingpres)) )
*__${CHANNEL}__: Current channel name
*__${CONTEXT}__: The name of the current context
*__${DATETIME}__: Current date time in the format: DDMMYYYY-HH:MM:SS
*__${DIALEDPEERNAME}__: Name of the called party. Broken for now, see ((DIALEDPEERNAME))
*__${DIALEDPEERNUMBER}__: Number of the called party. Broken for now, see ((DIALEDPEERNUMBER))
*__${DIALEDTIME}__: Time when the number was dialed.
*__${DIALSTATUS}__: Status of the call. See ((DIALSTATUS))
*__${DNID}__: Dialed Number Identifier. Limitations apply, see ((DNID))
*__${EPOCH}__: The current UNIX-style epoch (number of seconds since 1 Jan 1970)
*__${EXTEN}__: The current extension
*__${((Asterisk variable hangupcause|HANGUPCAUSE))}__: The last hangup return code on a Zap channel connected to a PRI interface
*__${INVALID_EXTEN}__: The extension asked for when redirected to the ((Asterisk i extension|i)) (invalid) extension
*__${LANGUAGE}__: The current language setting. See ((Asterisk multi-language))
*__${MEETMESECS}__: Number of seconds a user participated in a MeetMe conference
*__${PRIORITY}__: The current priority
*__${RDNIS}__: The current redirecting ((DNIS)), Caller ID that redirected the call. Limitations apply, see ((RDNIS))
*__${SIPDOMAIN}__: SIP destination domain of an inbound call (if appropriate)
*__${SIP_CODEC}__: Used to set the SIP codec for a call ([http://bugs.digium.com/bug_view_page.php?bug_id=0000450|apparently broken in Ver 1.0.1], ok in Ver. 1.0.3 & 1.0.4, not sure about 1.0.2)
*__${SIPCALLID}__: The SIP dialog Call-ID: header
*__${SIPUSERAGENT}__: The SIP user agent header
*__${TIMESTAMP}__: Current date time in the format: YYYYMMDD-HHMMSS
*__${TXTCIDNAME}__: Result of application TXTCIDName (see below)
*__${UNIQUEID}__: Current call unique identifier
*__${TOUCH_MONITOR}__: used for “one touch record” (see features.conf, and wW dial flags). If is set on either side of the call then that var contains the app_args for app_monitor otherwise the default of WAV||m is used

!!!Application-specific variables
Some applications take extra input or provide output using channel variables.
*((Asterisk cmd ChanIsAvail|ChanIsAvail)) returns __${AVAILCHAN}__: The first available channel
*((Asterisk cmd Dial|Dial)) takes input from __${VXML_URL}__: Send XML Url to Cisco 7960
*((Asterisk cmd Dial|Dial)) takes input from __${ALERT_INFO}__: Set ring cadence or allow intercom on for various SIP phones
*((Asterisk cmd Dial|Dial)) returns __${CAUSECODE}__: If the dial failed, this is the errormessage
*((Asterisk cmd Dial|Dial)) returns __${((Asterisk variable DIALSTATUS|DIALSTATUS))}__: Text code returning status of last dial attempt.
*((Asterisk cmd Dial|Dial)) takes input from __${TRANSFER_CONTEXT}__: If this variable exists, when a #transfer is executed it goes to the selected extension on this context.
* ((Asterisk cmd EnumLookup|EnumLookup)) returns __${ENUM}__: The result of the lookup
*((Asterisk cmd MeetMe|MeetMe)) takes input from __{MEETME_AGI_BACKGROUND}__: An AGI script to run
*((Asterisk cmd MeetMe|MeetMe)) returns __${MEETMESECS}__: The number of seconds the user was in a conference
* ((Asterisk cmd Hangup|Hangup)) reads the __${((Asterisk variable PRI_CAUSE|PRI_CAUSE))}__ variable for setting PRI return codes
* ((Asterisk cmd TXTCIDName|TXTCIDName)) returns __${TXTCIDNAME}__: The result of the DNS lookup
* ((Asterisk cmd AgentCallbackLogin|AgentCallbackLogin)) returns __${AGENTBYCALLERID_${CALLERID}}__: The ID of the agent successfully logged on.

!!!Macro-specific variables
When in a ((Asterisk cmd Macro|macro context)), extra channel variables are available.
*${ARG1}: The first argument passed to the macro
*${ARG2}: The second argument passed to the macro (”and so on”)
*${MACRO_CONTEXT}: The context of the extension that triggered this macro
*${MACRO_EXTEN}: The extension that triggered this macro
*${MACRO_OFFSET}: Set by a macro to influence the priority where execution will continue after exiting the macro
*${MACRO_PRIORITY}: The priority in the extension where this macro was triggered

!!Environment Variables
You may access unix environment variables using the syntax:

${ENV(”foo”)}

*__${ENV(ASTERISK_PROMPT)}__: the current Asterisk ((Asterisk CLI prompt|CLI prompt)).
* __${ENV(RECORDED_FILE)}__: the filename of the last file saved by the ((Asterisk cmd Record|Record)) command (available in CVS > 2004-03-21)

!String Handling Functions
!!String Length

${LEN(foo)}

returns the length of the string ”foo”. For example,

exten => 100,1,SetVar(Fruit=pear)
exten => 100,2,NoOp(${LEN(Fruit)})
exten => 100,3,NoOp(${LEN(${Fruit})})

The first NoOp would show a value of 5 (the length of the string “fruit”). The second NoOp would show a value of 4 (the length of the string “pear”).

__This is an excellent way to check for a NULL or empty string.__

!!Substrings
${foo:”offset”:”length”}

returns a substring of the string ”foo”, beginning at offset ”offset” and returning the next ”length” characters.
*If ”offset” is negative, it is taken leftwards from the right hand end of the string.
*If ”length” is omitted or is negative, then all the rest of the string beginning at ”offset” is returned.

Examples:

${123456789:1} – returns the string 23456789
${123456789:-4} – returns the string 6789
${123456789:0:3} – returns the string 123
${123456789:2:3} – returns the string 345
${123456789:-4:3} – returns the string 678

Examples of use:

exten => _NXX.,1,SetVar(areacode=${EXTEN:0:3}) – get the first 3 digits of ${EXTEN}
exten => _516XXXXXXX,1,Dial(${EXTEN:3}) – get all but the first 3 digits of ${EXTEN}
exten => 100,1,SetVar(whichVowel=4)
exten => 100,2,SetVar(foo=AEIOU:${whichVowel}:1) – sets ${foo} to the single letter ‘U’

!!String Concatenation
To concatenate two strings, simply write them together:

${foo}${bar}
555${theNumber}
${longDistancePrefix}555${theNumber}

!! Variable math
To perform math on variables e.g. increment, multiplication, addition simply write:

exten => s,1,SetVar(SOMEVAR=$[[${SOMEVAR} + 1]) ; increment
exten => s,2,SetVar(SOMEVAR=$[[2 * ${SOMEVAR}]) ; multiplication etc…
__In times past, a single space was required between items in the ~np~$[…] ~/np~expressions. This is no longer the case! __

In late model Asterisks (1.2?), the MATH function is also available…

exten => s,1,Set(SOMEVAR=${MATH(${SOMEVAR}+1)}) ; increment
exten => s,2,Set(SOMEVAR=${MATH(2*${SOMEVAR})}) ; multiplication etc…

!!Version notes
* CALLINGPRES was added to CVS HEAD 2004-09-10, included in Asterisk 1.2 release
* TOUCH_MONITOR was added to CVS HEAD 2005-01-05, included in Asterisk 1.2 release

!See also
* ((Asterisk Functions)) Besides the ENV(), and LEN() functions, there are many more very useful functions. Some form the only method by which you can access or set certain facilities in Asterisk.
* ((Asterisk Expressions)) Asterisk has a powerful expression evaluator! It is called upon by wrapping an expression with ~np~$[ … ] ~/np~. Besides arithmetic expressions, there are some nice string manipulation capabilities.
*((Asterisk cmd Cut|Cut)): Extract a substring based on a field delimiter

—-
((Asterisk)) | ((Asterisk config files|Configuration)) | ((Asterisk config extensions.conf|The Dialplan – extensions.conf))info