0

I sometimes want to run a Tmux command across all panes in a single or multiple sessions to e.g. clean up my working environment.

An example would be to execute this Tmux command:

# Clear screen
bind M-l send-keys -R \; clear-history \; send-keys C-l \; display "█▓░ clear"

I know of the synchronize-panes window option, but AFAIK it only synchronize panes in the current window, and not all panes in all sessions:

# Synchronize panes (toggle option)
bind C-s setw synchronize-panes \; display "█▓░ synchronize (#{?synchronize-panes,on,off})"

Is there a way to run a Tmux command across all panes in a single session or multiple sessions?

1 Answer 1

1

Here is a script I wrote to do this. Save it as tmux-sendall (chmod +x tmux-sendall):

#!/bin/bash

if [[ -z $1 ]]; then
    current=$(tmux display -p "#S")
    echo "usage: tmux-sendall SESSION [COMMAND]"
    if [[ -n $current ]]; then
        echo "current session: $current"
    fi
    exit 1
else
    session="$1"
fi

if [[ -n $2 ]]; then
    message="$2"
else
    read -p "send cmd to session $session$ " message
    if [[ -z $message ]]; then exit 1; fi
fi

function sendwindow() {
    # $1=target, $2=command
    tmux setw -t $1 synchronize-panes
    tmux send-keys -lt "$1" "$2"
    tmux send-keys -t "$1" "Enter"
    tmux setw -t $1 synchronize-panes off
}

export -f sendwindow
tmux list-windows -t $session | cut -d: -f1 | xargs -I{} bash -c "sendwindow '$session:{}' '$message'"

It lists the windows for the given session and then executes the sendwindow function for each one.

You can customize the sendwindow function with tmux commands if you want it to do something else.

Example, assuming you have a session named 1:

tmux-sendall 1 "echo hello world"
4
  • Thank you. How would I execute my key-binding above, M-l? Would I need to run your script as tmux-sendall 1 'send-keys -R \; clear-history \; send-keys C-l \; display "█▓░ clear"', or could I run it with M-l as second argument?
    – Shuzheng
    Oct 6, 2020 at 8:41
  • You threw me off because you were using send-keys. This function is for sending keys (as if you were typing into the panes). If you simply want to execute a tmux command you can run it without all of this - see the -t option: clear-history [-t target-pane]
    – laktak
    Oct 6, 2020 at 8:47
  • Ahh, I see. So there is no way to say to Tmux: "run my M-l key-binding in all sessions"? I have tried your script with C-a M-l, but it doesn't seem that send-keys can run key-bindings?
    – Shuzheng
    Oct 6, 2020 at 10:23
  • My script disables these because it is meant to send text. You can try to remove the -l flag from send-keys, change -lt to -t.
    – laktak
    Oct 6, 2020 at 11:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .