Variables
Variables store values during script execution. They are created by capture-window and run commands and referenced with the $ prefix.
Creating Variables
From capture-window
Captures a window reference (window ID) for use with record:
capture-window app "Terminal" as $term
capture-window id 12345 as $win
record $term duration 5 continue
From run
Captures shell command output:
run "git log --oneline -5" as $log
run "cat /etc/hosts" as $hosts
run "echo hello" as $greeting
The variable stores the full stdout output. Individual lines are accessible via indexing.
Indexing
Access individual output lines with $var[N] (0-indexed):
run "git log --oneline -3" as $log
# $log[0] = first line (most recent commit)
# $log[1] = second line
# $log[2] = third line
spotlight stdout $log[0] duration 2
spotlight-shift stdout $log[2] duration 1.5
Accessing an index beyond the available lines causes a runtime error. If the command outputs 3 lines, $log[3] will fail.
Special Variables
$_exitcode
Set after every run command with the exit code of the shell command:
run "ls /nonexistent"
# $_exitcode is now non-zero (e.g., 1)
run "echo hello"
# $_exitcode is now 0
In strict mode (default: on), a non-zero exit code causes the script to fail immediately. Disable with set strict false to check $_exitcode manually.
$var_stderr
When a run command produces stderr output, a companion variable is created with the _stderr suffix:
run "ls /nonexistent" as $result
# $result = "" (empty stdout)
# $result_stderr = "ls: /nonexistent: No such file or directory"
The _stderr variable is only created when stderr is non-empty.
String Interpolation
Variables can be interpolated inside quoted strings using $name:
run "whoami" as $user
type "Hello, $user!" enter
The engine replaces $user with the variable's value before executing the command.
If a variable is undefined during interpolation, the literal $name text is preserved and a warning is logged. This does not cause a script error.
Variable Types
Variables can hold three types of values:
| Type | Created By | Access |
|---|---|---|
| Window ID | capture-window | $var returns the numeric window ID |
| String | run (single-line output) | $var returns the full string |
| Lines | run (multi-line output) | $var returns all lines joined by newlines; $var[N] returns line N |
All types convert to strings when used in type, spotlight, or string interpolation contexts.