Run or send a command to a tmux pane in a running tmux session

bashshelltmux

I want to write a shell script which will attach to a named tmux session, select a window (or pane) in that session and run a command in that selected window (or pane).

How do I do this from a bash script?

I know

tmux new-window -n:mywindow 'exec something'

allows me to send commands to a freshly created window, but I need something like

tmux select-window -t:0 'my command'

I suppose I could use send-keys but seems like there should be something that takes a command or list of commands that get run.

Best Answer

Each tmux pane is an interface for a single pty (pseudo tty). Non-split windows have a single pane; split windows have multiple panes.

tmux does not supply a way to add extra processes to a pane once it has been started with its initial command. It is up to that initial command’s process (usually a shell) to supply job control1 for that terminal.

If you want to clobber whatever is currently running in the pane, you can use respawn-pane -k to kill the existing command and replace it with a new one (e.g., respawn-pane -t sessionname:0.4 -k 'some -new command').

But, if you want to maintain whatever is currently running in the pane, then there may be no better option that simply “typing at it” with send-keys.

You might script it like this (attach last, because otherwise the script will just wait for you to detach before continuing):

session=whatever
window=${session}:0
pane=${window}.4
tmux send-keys -t "$pane" C-z 'some -new command' Enter
tmux select-pane -t "$pane"
tmux select-window -t "$window"
tmux attach-session -t "$session"

Note that, on the send-keys command, you should actually type the letters E n t e r, to tell tmux to send a newline key to the window.  (Naturally, every command ends with the Enter key.)


1Job control is the arbitration between multiple process groups of a single session that uses the tty as its controlling terminal. I.e., the Ctrl+Z suspend key, and the jobs, fg, and bg shell commands.

Related Question