4

I would like to automate the following steps that I am currently performing manually.

In a terminal, I perform these steps:

  1. start tmux
  2. split into 10 panes
  3. tile the panes
  4. navigate to each pane and ssh into a server, repeat 10 times
  5. synchronize the panes

Is there a way to script all this, including the 10 different ssh login commands?

1
  • What have you tried? The tmux manual tells you how to do all of this, e.g. tmux split-window will create a new pane, and tmux send-keys can send commands to start an ssh session.
    – icarus
    Aug 3, 2019 at 4:03

1 Answer 1

11

The new-session and split-pane commands in tmux take a command to run in the new pane. If you have a list of user@server strings in an array, you could do this:

#!/bin/bash

ssh_list=( user1@server1 user2@server2 ... )

split_list=()
for ssh_entry in "${ssh_list[@]:1}"; do
    split_list+=( split-pane ssh "$ssh_entry" ';' )
done

tmux new-session ssh "${ssh_list[0]}" ';' \
    "${split_list[@]}" \
    select-layout tiled ';' \
    set-option -w synchronize-panes

This creates a list of split-pane commands that split the current pane and run ssh to one of the servers in the list ssh_list. We create one such command for each of the listed servers, except for the first one (which we will use with the new-session command instead).

The tmux command at the end creates a new session and runs the first ssh command, does all the splits, rearranges the panes according to the tiled layout (see the tmux manual for alternatives), and enables synchronisation of the panes.

The tmux session will terminate once all ssh sessions have terminated.


Update: Interestingly, the tmux(1) manual does not mention a split-pane command. The above code still works though, but if you're using an older version of tmux, you may want to change split-pane into split-window (since tmux 2.4, split-pane and splitp are synonyms for split-window).

1
  • 1
    how would you go about naming the panes? I saw that it's not trivial to name them. Opening a bunch of windows instead is also an option. but the automatic naming is important for me. For example, name them based on the host name (or simply by enumeration)
    – lazary
    Apr 28, 2020 at 14:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.