Skip to main content

Non-Interactive and Cron Jobs

Tmux can be used from scripts, cron jobs, and CI pipelines to start background sessions, inject commands, and monitor running processes without a terminal.

Key Insight

You do not need to be inside tmux to run tmux commands. All tmux commands work from any shell — including cron jobs.

Starting a Detached Session from a Script

#!/bin/bash
# Start a background job in a tmux session
tmux new-session -d -s "backup-job" "rsync -av /data /backup && echo done"

The -d flag starts the session detached — no terminal needed.

Checking If a Session Is Running

if tmux has-session -t backup-job 2>/dev/null; then
echo "Backup session already running"
else
tmux new -d -s backup-job "rsync -av /data /backup"
echo "Backup session started"
fi

Sending Commands to a Running Session

# Wake up a pane and send a command
tmux send-keys -t work:logs "tail -f /var/log/newapp.log" Enter

# Send a signal to stop a running command
tmux send-keys -t work:server "C-c" ""
warning

send-keys with C-c sends a literal Ctrl+C to the pane. Use carefully — it interrupts the running process.

Example: Cron-Based Backup via Tmux

/etc/cron.d/backup
0 2 * * * root /usr/local/bin/tmux-backup.sh
/usr/local/bin/tmux-backup.sh
#!/bin/bash
SESSION="backup-$(date +%Y%m%d)"

# Start the session if not already running
if ! tmux has-session -t "$SESSION" 2>/dev/null; then
tmux new -d -s "$SESSION" "rsync -av /srv/data /backup/$(date +%Y%m%d) && echo OK"
fi
note

Cron runs with a minimal environment. If tmux is not in PATH, use the full path: /usr/bin/tmux.

Logging Output from a Tmux Session

# Enable logging for a pane (logs to a file)
tmux pipe-pane -o -t work:logs "cat >> /var/log/tmux-logs/work-logs.log"

# Stop logging
tmux pipe-pane -t work:logs

Waiting for a Process in a Tmux Pane

#!/bin/bash
SESSION="build"
tmux new -d -s "$SESSION" "make all && touch /tmp/build-done"

# Poll until done
echo "Waiting for build..."
while ! [ -f /tmp/build-done ]; do
sleep 5
done
echo "Build complete."
rm /tmp/build-done

Injecting Commands from CI

In CI pipelines (GitHub Actions, GitLab, etc.), you typically do not have a display — but if building a dev environment script:

# Run a test inside an existing tmux session on a dev server
ssh user@dev-server "tmux send-keys -t dev:tests 'npm test' Enter"

Common Pitfalls

PitfallSymptomFix
No DISPLAY or DBUS_SESSION_BUS_ADDRESSGUI clipboard failsUse file-based or tmux-buffer output instead
Tmux not in cron PATHtmux: command not foundUse /usr/bin/tmux full path
Session already existsScript fails or creates duplicateAlways check has-session first

What's Next