Asterisk Gosub Subroutines: Dialplan Guide and Examples
Asterisk Gosub subroutines explained: write, call and pass arguments in extensions.conf, return values, and use Dial b, B, U options and hangup handlers.
By Arkay · Updated · Published

What is a Gosub subroutine in the Asterisk dialplan?
Gosub jumps to a label in the dialplan and saves the return address. Return() then sends the call back to the line after the Gosub. That saved return address is what separates a subroutine from a simple jump, because the caller can pick up where it left off.
The Asterisk Gosub configuration guide notes that no special syntax is needed to define a subroutine. A subroutine is an ordinary dialplan context. When it should send the call back, it calls Return.
Gosub takes the form Gosub([[context,]extension,]priority[(arg1,...,argN)]). Only the priority is required, so the context, the extension and the arguments are all optional. The Gosub application reference says Gosub has been available since Asterisk 1.2.0.
How do you write and call a subroutine in extensions.conf?
In extensions.conf, a subroutine is written like any other context. The example below is adapted from the official Gosub guide. It defines a subroutine context and calls it from a second context.
[my-gosub]
exten => s,1,Playback(tt-weasels)
same => n,Return()
[somecontext]
exten => sales,1,NoOp(Caller dialed sales)
same => n,Gosub(my-gosub,s,1)
same => n,Dial(PJSIP/alice)
The first line, [my-gosub], starts the subroutine context. The line exten => s,1,Playback(tt-weasels) starts at extension s, priority 1, and plays the tt-weasels prompt. The s extension is the entry point the official example uses.
The line same => n,Return() sends the call back. The word same means the step belongs to the same extension as the line above it, and n is the next priority.
In the second context, the Gosub(my-gosub,s,1) line jumps to extension s, priority 1 of my-gosub. When Return() runs, the call continues at the next line, which is the Dial. PJSIP/alice is only an example endpoint name.
How do you pass arguments and return a value?
Put arguments in parentheses after the priority, separated by commas. The subroutine reads the first as ${ARG1}, the second as ${ARG2}, and so on. The Gosub configuration guide shows Gosub(my-gosub,s,1(${EXTEN})), which passes the extension as the first argument.
[my-gosub]
exten => s,1,NoOp(ARG1 is ${ARG1} and ARG2 is ${ARG2})
same => n,Return()
[somecontext]
exten => greet,1,Gosub(my-gosub,s,1(${EXTEN},alpha))
The NoOp line writes both arguments to the output, so you can see what the subroutine received. In the caller, ${EXTEN} holds the extension that matched, which is greet here. So ARG1 becomes greet, and ARG2 becomes alpha. The commas inside the parentheses separate the two arguments.
Return can also send a value back. The Return reference says Return([value]) saves the value in the channel variable GOSUB_RETVAL. The caller reads it after the Gosub. Return has been available since Asterisk 1.2.0.
LOCAL(varname) keeps a variable inside the subroutine's own stack frame. It has been available since Asterisk 1.6.1.0. After Return() the variable is lost or reverts to its earlier value, so anything the caller needs must leave through Return(value).
[get-greeting]
exten => s,1,Set(LOCAL(greeting)=hello)
same => n,Return(${LOCAL(greeting)})
[somecontext]
exten => greet,1,Gosub(get-greeting,s,1)
same => n,NoOp(Subroutine returned ${GOSUB_RETVAL})
The Set line stores hello in a local variable. The Return line reads that variable before it returns, and passes the value back. The caller's NoOp line then reads the value from GOSUB_RETVAL. The variable greeting is gone after Return, but the value has already travelled with the return.
What are all the ways to call a subroutine?
We compiled this table from the official Asterisk documentation on November 14, 2026. The API reference pages say they were generated from Asterisk branch 23. The table has not been run on a live system.
| Method | Syntax | Separator | How a result comes back |
|---|---|---|---|
| Gosub | Gosub([[context,]extension,]priority[(arg1,...,argN)]) | commas | Jumps to the label and saves the return address. Since 1.2.0. |
| GosubIf | GosubIf(condition?[labeliftrue:[labeliffalse]]) | labels as in Goto() | Jumps to labeliftrue if the condition is true, or to labeliffalse if it is given. Since 1.2.0. |
| Return | Return([value]) | none | The value is saved in GOSUB_RETVAL. Since 1.2.0. |
| Dial option U | U(x^arg) | ^ | Runs routine x on the called channel before it connects. The routine can set GOSUB_RESULT. |
| Dial option b | b(context^exten^priority) | ^ | Pre-dial handler on each new outgoing channel. Asterisk 11 and later. |
| Dial option B | B(context^exten^priority) | ^ | Pre-dial handler on the calling channel. Asterisk 11 and later. |
| hangup_handler_push | Set(CHANNEL(hangup_handler_push)=[[context,]exten,]priority[(arg1,...,argN)]) | commas | Runs when the channel hangs up. The most recently added runs first. Asterisk 11 and later. |
| Macro (legacy) | Macro | commas | Deprecated. The docs say to use Gosub instead. |
The rows fall into two groups. Gosub, GosubIf and Return control the flow of the dialplan itself. The other rows attach a subroutine to something else: a Dial option, or the channel's hangup.
The key gotcha is the separator. Gosub and hangup_handler_push separate arguments with commas, but the Dial options b, B and U use ^. Also, GOSUB_RESULT, which a U() routine sets, is not GOSUB_RETVAL, which Return() sets.
How do you call a subroutine only when a condition is true?
GosubIf is the conditional form of Gosub. Its syntax is GosubIf(condition?[labeliftrue:[labeliffalse]]). The question mark separates the condition from the labels. The colon separates the label for a true condition from the label for a false one.
Labels take the Goto() form, [[context,]extension,]priority. If the condition is true, the call jumps to the true label. If the condition is false, the call jumps to the false label, when one is given. The false label is optional, as the square brackets in the syntax show.
The GosubIf reference says that in either case, a jump saves the return point in the dialplan. A Return() in the target routine therefore sends the call back to the line after the GosubIf. GosubIf has been available since Asterisk 1.2.0.
[somecontext]
exten => vip-check,1,GosubIf($[${VIP}]?vip-routine,s,1:standard-routine,s,1)
same => n,Dial(PJSIP/alice)
[vip-routine]
exten => s,1,NoOp(VIP caller)
same => n,Return()
[standard-routine]
exten => s,1,NoOp(Standard caller)
same => n,Return()
The condition is written as $[${VIP}]. VIP is a variable that your dialplan sets earlier, for example with Set(). If it is true, the call jumps to s, priority 1 of vip-routine. If it is false, the call jumps to s, priority 1 of standard-routine. Each routine ends with Return(), so the call comes back to the Dial line in both cases.
How do you run subroutines from Dial with b, B and U?

Dial has three options that run a subroutine. The b() and B() options are pre-dial handlers, added in Asterisk 11. A pre-dial handler is a Gosub subroutine, so it must end with Return(). The b() handler runs on each new outgoing channel before the call is placed. The B() handler runs on the calling channel before the outgoing calls start.
Keep pre-dial handlers short. The pre-dial handler page says they must not move the caller or callee channel into other applications, which is undefined behavior. If context or exten are left out, the caller's current values are used.
[somecontext]
exten => ring,1,Dial(PJSIP/alice,,b(default^called_channel^1(my_gosub_arg1^my_gosub_arg2))B(default^callee_channel^1(my_gosub_arg1^my_gosub_arg2)))
[default]
exten => called_channel,1,NoOp(ARG1=${ARG1} ARG2=${ARG2})
same => n,Return()
exten => callee_channel,1,NoOp(ARG1=${ARG1} ARG2=${ARG2})
same => n,Return()
Read the b() option from the inside out. It names the context default, the extension called_channel and priority 1. Its two arguments follow in parentheses, separated by ^. The B() option does the same for callee_channel, but runs it on the calling channel. Each handler reads its arguments as ARG1 and ARG2 and ends with Return().
The U() option is different. It runs its routine on the called channel before that channel is connected to the caller. Its arguments also use ^. The first field is the routine name, and the fields after it are the arguments.
[my_gosub_routine]
exten => s,1,NoOp(ARG1=${ARG1} ARG2=${ARG2})
same => n,Playback(hello)
same => n,Return()
[somecontext]
exten => ring,1,Dial(PJSIP/alice,,U(my_gosub_routine^my_gosub_arg1^my_gosub_arg2))
A U() routine can set GOSUB_RESULT to ABORT, CONGESTION, BUSY, CONTINUE or GOTO:[[context^]exten^]priority. ABORT hangs up both legs. CONTINUE hangs up the called party and lets the caller continue at the next priority. GOTO transfers the call.
The U() routine also has limits. TIMEOUT() cannot be set inside it, because the PBX services run on the called channel. No other post-answer action options can be combined with U(), so plan the call flow around that.
How do hangup handlers work?
A hangup handler is a subroutine attached to a channel. It runs when that channel hangs up, wherever the channel is in the dialplan. Hangup handlers were added in Asterisk 11. You attach one with Set(CHANNEL(hangup_handler_push)=...).
[somecontext]
exten => ring,1,Set(CHANNEL(hangup_handler_push)=cleanup,s,1(${EXTEN}))
same => n,Dial(PJSIP/alice)
[cleanup]
exten => s,1,NoOp(Hangup handler ran for ${ARG1})
same => n,Return()
The Set line attaches the routine cleanup, at s, priority 1, and passes ${EXTEN} as its argument. The attachment happens before the Dial runs. When the channel hangs up, the handler runs, and its NoOp line writes the extension name it received. The Return() line ends the handler.
Each handler must end with Return(). When several are attached, the most recently added one runs first. The hangup_handler_pop function removes or replaces the most recent handler, and hangup_handler_wipe clears the whole stack. To list the handlers on all channels, use core show hanguphandlers all.
Adding a handler in the h extension, or during a hangup handler, is undefined behavior. Handlers run in the hangup path, so keep them quick.
Should you still use Macro?
No. The Gosub page says Macro has issues with nesting, that Gosub does not, and that Gosub should be used wherever Macro was used. The Macro page is kept for historical purposes.
Macro passed arguments as ARG1 and ARG2, and stored the caller's location in MACRO_EXTEN, MACRO_CONTEXT and MACRO_PRIORITY. Moving a Macro call to Gosub is mostly mechanical. Put the arguments in parentheses after the priority, separated by commas, and keep reading them as ARG1 and ARG2.
What goes wrong, and how do you check?
Most subroutine problems fail in a few predictable ways. The table below lists each symptom with the check that finds it. When a Dial option misbehaves, check that its arguments are separated with ^, as the docs describe.
| Symptom | What to check |
|---|---|
| Dial option arguments arrive wrong or empty | Inside b(), B() and U(), separate arguments with ^. Commas belong to Gosub and hangup_handler_push. |
| GOSUB_RETVAL is empty after a U() routine | A U() routine reports through GOSUB_RESULT. GOSUB_RETVAL is set only by Return(value). |
| GOSUB_RETVAL is empty after a Gosub | Check that the routine calls Return with a value. LOCAL values are lost after Return, so put the value inside Return(). |
| A b() or B() pre-dial handler misbehaves | Each pre-dial handler must end with Return(), because pre-dial handlers are Gosub subroutines. It must not move the channel into other applications. |
| A hangup handler does not seem to run | Confirm its routine ends with Return(). List the attached handlers with core show hanguphandlers all. |
| A handler added in the h extension, or inside a handler, behaves unpredictably | Adding a hangup handler there is undefined behavior. Attach handlers in the normal dialplan flow instead. |
| A TIMEOUT() setting inside a U() routine | TIMEOUT() cannot be set in that routine. Set the timeout outside it. |
| A variable is empty after a subroutine returns | LOCAL is lost after Return or reverts to its earlier value. Pass the value through Return(value). |
| GosubIf does not jump where you expect | Labels take the form [[context,]extension,]priority. Check both the true label and the false label. |
| STACK_PEEK prints an error | The optional suppress argument stops the error when n is higher than the number of frames available. |
| Macro arguments are missing after moving to Gosub | Gosub arguments go in parentheses after the priority, separated by commas, and are read as ARG1 and ARG2. |
The hangup and pre-dial rows come down to the same habit. Every handler is a subroutine, so it needs a Return() at the end, and each one should be short.
What do advanced Asterisk dialplan examples look like?
These three examples combine the pieces above, and each uses only documented parts. The extension names and values such as alice and blue are examples.
Example 1 is a subroutine that takes arguments, keeps a local variable and returns a value.
; Subroutine: reads ARG1 and ARG2, keeps ARG1 in a local variable, returns it
[greet-caller]
exten => s,1,NoOp(Greeting for ${ARG1}, second argument ${ARG2})
same => n,Set(LOCAL(name)=${ARG1})
same => n,Playback(hello)
same => n,Return(${LOCAL(name)})
; Caller passes two arguments and reads the returned value
[somecontext]
exten => greet,1,Gosub(greet-caller,s,1(alice,blue))
same => n,NoOp(Subroutine returned ${GOSUB_RETVAL})
The subroutine writes its arguments, stores ARG1 in a local variable, plays a prompt and returns the stored name. LOCAL(name) lives in this call's stack frame, so the value must leave through Return(). The caller then finds it in GOSUB_RETVAL.
Example 2 is a conditional subroutine with hangup cleanup. The caller attaches a cleanup handler first, so the cleanup runs when the call ends, and then chooses a routine with GosubIf.
; Caller: attach a cleanup handler, then choose a subroutine with GosubIf
[somecontext]
exten => vip-check,1,Set(CHANNEL(hangup_handler_push)=cleanup,s,1)
same => n,GosubIf($[${VIP}]?vip-routine,s,1:standard-routine,s,1)
same => n,Dial(PJSIP/alice)
; Each routine ends with Return()
[vip-routine]
exten => s,1,NoOp(VIP caller)
same => n,Return()
[standard-routine]
exten => s,1,NoOp(Standard caller)
same => n,Return()
[cleanup]
exten => s,1,NoOp(Call ended)
same => n,Return()
The Set line attaches the hangup handler before anything else happens. The GosubIf line then runs one of the two routines, depending on VIP. Both routines end with Return(), so the call returns to the Dial line. When the call ends, the cleanup routine runs and writes its message.
Example 3 is a debug trace that uses STACK_PEEK.
; Prints the context, extension and priority n frames up the Gosub stack
[debug-trace]
exten => s,1,NoOp(Called from ${STACK_PEEK(1,c)} ${STACK_PEEK(1,e)} ${STACK_PEEK(1,p)})
same => n,Return()
[somecontext]
exten => debug,1,Gosub(debug-trace,s,1)
STACK_PEEK(n,which) reads the calling context (c), extension (e), priority (p) or label (l), going up n frames in the Gosub stack. Here n is 1. The page does not say which frame each value of n points to, so check the output in your own dialplan before you rely on it. The optional third argument, suppress, stops the error message when n is higher than the number of frames available.
More guides in Open-Source PBX and SIP Servers.
Related guides
Frequently asked questions
- Why do Dial options use ^ instead of commas to separate arguments?
- Dial options b, B and U separate their arguments with ^. Gosub and hangup_handler_push use commas. Use ^ inside b(), B() and U(), and commas in Gosub and hangup_handler_push.
- How do you keep variables local to a subroutine?
- Use LOCAL(varname) inside the subroutine. It has been available since Asterisk 1.6.1.0. After Return() the variable is lost or reverts to its earlier value, so pass results back with Return(value).
Sources
- The Gosub configuration guide gives the call form Gosub([[context,]exten,]priority[(arg1[, (docs.asterisk.org)
- Gosub jumps to a dialplan label and saves the return address; its syntax is Gosub([[contex (docs.asterisk.org)
- Return([value]) jumps back to the last label on the stack; the optional return value is sa (docs.asterisk.org)
- GosubIf(condition?[labeliftrue:[labeliffalse]]) jumps to labeliftrue if the condition is t (docs.asterisk.org)
- Pre-dial handlers were added in Asterisk 11; they are Gosub subroutines and must end with (docs.asterisk.org)
- The Macro page is kept for historical purposes; the docs say to use Gosub wherever Macro w (docs.asterisk.org)