Skip to main content

Introduction to tmux Scripting

tmux provides powerful scripting capabilities that allow you to:
  • Automate session and window creation
  • Execute conditional logic
  • Run shell commands in the background
  • Display formatted information
  • Load and organize configuration files
All tmux commands can be scripted, whether from configuration files, shell scripts, or key bindings.

The if-shell Command

The if-shell command executes tmux commands conditionally based on shell command results.

Basic Syntax

Simple Conditional

Background Execution

Format Expansion

Use -F to treat the shell command as a format string instead of executing it:

Real-World Examples

Nested if-shell

You can nest if-shell commands:
Be careful with nested if-shell commands as they can become difficult to read and debug. Consider using format-based conditionals with -F instead.

The run-shell Command

The run-shell command executes shell commands in the background without creating a window.

Basic Syntax

Simple Execution

Output Display

By default, command output is shown in view mode:

Running tmux Commands

Use -C to run tmux commands instead of shell commands:

Delayed Execution

Working Directory

Practical Examples

The display-message Command

The display-message command shows messages and evaluates formats.

Basic Display

Format Expansion

Display formatted information:

Script Integration

Verbose Mode and Debugging

Forwarding Input

The source-file Command

The source-file command loads and executes tmux commands from files.

Basic Usage

Format Expansion

Parse Without Executing

Organized Configuration

Split configuration into multiple files:

Conditional Loading

Advanced Scripting Patterns

Command Sequences

Chain multiple commands:

Using Formats in Scripts

Session Management Scripts

Error Handling

Environment Variables in Scripts

tmux provides useful environment variables:

Setting Environment Variables

Complete Scripting Example

A comprehensive project setup script:
Use it: