How to send a command to all panes in tmux? - tmux

I like to call :clear-history on panes with a huge scrollback. However, I want to script a way to send this command to all the panes in the various windows.
I know how to send a command to all the windows, courtesy of this question, but how do I send a command to all the panes of which window as well?
send-keys and synchronize-panes from the tmux manpage come to mind, but I'm not sure how to marry them together. But maybe there is a simpler way to do this.
Extra Observations:
Thinking about this a little bit, tmux list-panes -a seems to list all the panes in the current session. Pretty useful to start off with. Where do I go from here?

Have you tried following in tmux window with multiple panes
Ctrl-B :
setw synchronize-panes on
clear history

A bit late to the party but I didn't want to set and unset synchronize-panes just to send one command so I created a wrapper function around tmux and added a custom function called send-keys-all-panes.
_tmux_send_keys_all_panes_ () {
for _pane in $(tmux list-panes -F '#P'); do
tmux send-keys -t ${_pane} "$#"
done
}
I also create a wrapper around the tmux command to simplify calling this function (for convenience). The wrapper and the above code are all here.
This allows me to run tmux send-keys-all-panes <command> or tmux skap <command to send <command> to all panes.
Note that tmux is aliased to my wrapper function tmux_pp.

Update June 2019
Quick illustration on how to configure your own binding for synchronize panes.
Added the following into my tmux.conf (the comments certainly apply to my overall configuration):
# synchronize all panes in a window
# don't use control S, too easily confused
# with navigation key sequences in tmux (show sessions)
unbind C-S
bind C-Y set-window-option synchronize-panes
Now, I can toggle the ability to synchronize commands across multiple panes with <C-a><C-y>.
(Yes, I remapped the bind key to Ctrl a).

my tmux version is 1.9a, and this works for me, one key is enough for both on and off
bind-key X set-window-option synchronize-panes\; display-message "synchronize-panes is now #{?pane_synchronized,on,off}"

None of the above answers worked for me (tmux v2.3), but this did, from the bash command line:
for _pane in $(tmux list-panes -a -F '#{pane_id}'); do \
tmux clear-history -t ${_pane} ; done
A more generalized script, for tmux commands other than 'clear-history' would just replace that element with a parameter, eg. $1. Do be careful if you intend to write a script to handle a series of tmux commands, as "-t ${_pane}" will need to be applied to each.
Note that the -a parameter to tmux list-panes is required to cover all panes in all windows in all sessions. Without that, only panes in your current tmux window will be affected. If you have more than one tmux session open and only want to apply the command to panes within the current session, replace -a with -s (It's all in the tmux man page).
I haven't the mod points to comment directly on each of the above answers, so here's why they weren't working for me:
The problem that I had with #shailesh-garg 's answer was that the sync affected only commands issued within the panes, not tmux commands issued using Ctrl-B : which are outside the panes.
The three problems that I had with #kshenoy 's answer were that:
it sends keystrokes to within a pane, not to the tmux operation
of that pane, so for instance, if one had a bash shell running in
the pane and one used the script to send "clear-history", those
would be the keystrokes that would appear in the bash command-line.
A work-around would be to send "tmux clear-history" or to pre-pend
"tmux " to "$#", but I haven't edited the answer because of my other
problems with the answer;
I couldn't figure out how to send a
new-line character without literally breaking the line;
Even when I did that, sending "tmux clear-history" had no effect.

If you want to send your command to every pane in every window in every session, add this to your .bashrc:
send_command_to_every_pane() {
for session in `tmux list-sessions -F '#S'`; do
for window in `tmux list-windows -t $session -F '#P' | sort`; do
for pane in `tmux list-panes -t $session:$window -F '#P' | sort`; do
tmux send-keys -t "$session:$window.$pane" "$*" C-m
done
done
done
}
You can then use it like this:
send_command_to_every_pane source ~/.bash_profile
Change "$*" to "$#" if you want that behavior, but in my experience this is what you want.

tmux send-keys -t <session id> <command> C-m
Replace the "session id" and "command" accordingly.

This is my utility function to do it, only executing the command when there there is nothing running in the pane.
#!/bin/bash
_send_bash_command_to_session() {
if [[ $# -eq 0 || "$1" = "--help" ]] ; then
echo 'Usage: _send_bash_command_to_session $session_name what ever command you want: '
return
fi
input_session="$1"
input_command="${#:2}"
for _pane in $(tmux list-panes -s -t ${input_session} -F '#{window_index}.#{pane_index}'); do
# only apply the command in bash or zsh panes.
_current_command=$(tmux display-message -p -t ${input_session}:${_pane} '#{pane_current_command}')
if [ ${_current_command} = zsh ] || [ ${_current_command} = bash ] ; then
tmux send-keys -t ${_pane} "${input_command}" Enter
fi
done
}
tmux_set_venv() {
_current_session=$(tmux display-message -p '#{session_name}')
_send_bash_command_to_session ${_current_session} workon $1
}
Example targeting a session called dev, enabling a python virtualenv in all panes that are in bash or zsh, avoiding executing the command in panes with vim or any other executable:
_send_bash_command_to_session dev workon myvirtualenv
or easier to remember: to do it in the current session:
tmux_set_venv myvirtualenv
Find my configuration file with this function.

You can combine synchronize-panes and send-keys in a single shortcut to send commands to all the panes:
Predefined tmux command clear-history:
bind-key C set-option -w synchronize-panes on\; clear-history \; set-option -w synchronize-panes off
Prompt an arbitrary tmux command:
bind-key p command-prompt -p "Panes command: " "set-option -w synchronize-panes on; %% ; set-option -w -u synchronize-panes"
Prompt an arbitrary shell command:
bind-key p command-prompt -p "Panes command: " "set-option -w synchronize-panes on; send-keys %%\\n ; set-option -w -u synchronize-panes"

By default, byobu uses tmux as backend. It's a wrapper that make things much easier:
Shift+F9:
Ctrl+F9:
Shift+F1

Admittedly only semi-related, I found I could make the status background red when I toggle synchronize-panes so it's obvious when I switch back to a window with an unknown synchronize-panes state:
bind-key C-x setw synchronize-panes on \; set-window-option status-bg red \; display-message "pane sync on"
bind-key M-x setw synchronize-panes off \; set-window-option status-bg default \; display-message "pane sync off"

Related

How do i switch the active tmux session inside a shell script

I am trying to create an automated clean shutdown of my opensimulator servers.
On each server, I have several Tmux sessions. Inside each session, there are several windows. In the following example, there are only two sessions to keep things simple.
sara#opensim:~$ tmux ls
Robust: 5 windows (created Tue May 12 22:08:28 2020)
Simulators01: 6 windows (created Tue May 12 23:30:38 2020)
sara#opensim:~$
In the full version, there will be 10+ Simulator sessions.
What I want to do is use a shell script to select a specific session. Every session will have a closedown shell script which looks similar to this:
#!/usr/bin/env bash
SESSION="InstancesTesting"
echo "checking for session - $SESSION"
SESSIONEXISTS=$(tmux list-sessions | grep $SESSION)
if [ "$SESSIONEXISTS" != "" ]
then
echo "session found"
tmux attach-session -d -t $SESSION
tmux select-window -t '0821'
tmux send-keys -t '0821' 'quit' C-m
tmux select-window -t '0900'
tmux send-keys -t '0900' 'quit' C-m
tmux select-window -t '0901'
tmux send-keys -t '0901' 'quit' C-m
tmux select-window -t '0910'
tmux send-keys -t '0910' 'quit' C-m
tmux select-window -t '0911'
tmux send-keys -t '0911' 'quit' C-m
tmux select-window -t '0920'
tmux send-keys -t '0920' 'quit' C-m
echo "finished shut down call for $SESSION"
else
echo "session not found skipping"
fi
The problem line is
tmux attach-session -d -t $SESSION
When it is run from a shell script, everything after that stops until the session is detached. However, without attaching the session only the windows of the last attached session can be accessed.
I can't simply kill the session at the end of the quit commands because the simular running inside each window can take up to 10 mins to shut down. Neither do I want to wait 10 mins between starting each shutdown. I want to set them all going then wait for the processes to close before doing a reboot.
What I need is to either:
1. Attach a session and allow the script to keep running without pressing ctrl+b D to detach.
or
2. Change the session which is being accessed without actually attaching it like the above example.
I have also tried
tmux switch-client SessionName
tmux switch-client -t SessionName
tmux switch-client -n
All of these return the same result
no current client
I have also tried
tmux send-keys -t 'WindowName' 'tmux choose-session' C-m
tmux send-keys -t 'WindowName' '0' C-m
Unfortunately, this option also states there is no client.
I am sure this must be possible, I am going round in circles, please help
There is no concept of a "selected session", clients have an attached session but outside tmux when you don't specify a session the choice of which to use is made separately each time. See here: https://github.com/tmux/tmux/wiki/Advanced-Use#the-default-target
But you shouldn't need it. You are already using -t to specify the window, use it to specify the session as well:
tmux send-keys -t "$SESSION:8021" 'quit' C-m
You don't need select-window either unless you later plan to attach, and then one select-window at the end would do. See https://github.com/tmux/tmux/wiki/Advanced-Use#command-targets for a description of targets.
You may also find the has-session command useful instead of using grep, or the -F flag to list-sessions.

How to bind Ctrl-Tab and Ctrl-Shift-Tab in tmux for mintty

I would like to bind CTRL+TAB and CTRL+SHIFT+TAB (without prefix) to tmux functions, under minTTY/cygwin.
I have tried the following tmux configuration:
set-option -gw xterm-keys on
bind-key -n C-Tab next-window
bind-key -n "^[[1;5I" next-window # tmux doesn't recognize
bind-key -n "\e[1;5I" next-window # tmux doesn't recognize
If I hit CTRL+TAB after launching tmux, I get a bell sound. If I hit it after the tmux prefix, it prints 1;5I.
I am using minTTY 2.2.3 under cygwin/Babun. I have disabled minTTY's handling of this key combo via its options (SwitchShortcuts=no in .minttyrc).
For reference, CTRL+TAB and CTRL+SHIFT+TAB work for cycling screen windows with the following .screenrc:
bindkey "^[[1;5I" next
bindkey "^[[1;6I" prev
I got here because I bumped into the same issue.
tmux now supports custom key bindings via user-keys - since August 2017, so if you can build tmux yourself, or once a new tmux version is released, it's possible like so:
set -s user-keys[0] "\e[1;5I"
set -s user-keys[1] "\e[1;6I"
bind-key -n User0 select-pane -t+
bind-key -n User1 select-pane -t-
Note that you must use double quotes and not single quotes or else it won't interpret \e correctly.
At the time of writing the example in the manual uses single quotes - https://github.com/tmux/tmux/issues/1043 , though it's likely to be fixed soon.

TMUX using HJKL to navigate panes

Standard TMUX is set to use ctrl-b + [up, down, left, right] when navigating between panes.
I would like to make it so that I can use ctrl-b (or the prefix of my choice) + [h,j,k,l].
I thought I had done this with the following vi key in my ~/.tmux.conf settings:
set -g status-keys vi
setw -g mode-keys vi
Yet this didn't seem to change anything (at least not what I was looking for). How can I get this to work. And yes my .tmux.conf is working properly. I can provide more info if needed.
Update:
Here is my full .tmux.conf after trying to get it to work:
set -g status-keys vi
setw -g mode-keys vi
set -g prefix C-a
unbind C-b
bind C-a send-prefix
# smart pane switching with awareness of vim splits
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R
Alternatively, I have tried using this w/ vim-tmux-navigator Vim plugin:
# smart pane switching with awareness of vim splits
bind -n C-h run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-h) || tmux select-pane -L"
bind -n C-j run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-j) || tmux select-pane -D"
bind -n C-k run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-k) || tmux select-pane -U"
bind -n C-l run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-l) || tmux select-pane -R"
bind -n C-\ run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys 'C-\\') || tmux select-pane -l"
source
Which also doesn't work either. I am a bit stumped.
You can do this as follows:
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R
Note that mode-keys refers to using vi-like navigation within a buffer and status-keys refers to using vi-like editing within the status bar, but neither refers to switching between panes.
Did you remember to source your ~/.tmux.conf file? After making any changes in this file you need to enter the following command to see any of the changes take place
tmux source-file ~/.tmux.conf
The Micah Smith's answer seems to work. But it doesn't have quite the same behaviour that we have with the arrow keys. With the arrows, if you are fast enough, you can hit prefix + arrow key multiple times and you are able to navigate multiple panes, using the same prefix hiy. Main difference:
With the arrows:
// to move 3 panes to the right
prefix + -> -> ->
With this hack:
// to move 3 panes to the right
(prefix + l) 3x
Still, to make this change, you need to update your ~/.tmux.conf file and then restart tmux sessions.
To be sure you don't have any tmux sessions you can run
$ tmux list-sessions
If you have some sessions running, run $ killall tmux and you should be good to go.
This☝️ was tested in a macbook, it should be the same for linux.
If you are looking for a modal mode for tmux (e.g. like in Vim text editor), there is a plugin tmux-modal that can be used to execute complex commands with just a few keystrokes. For example:
w h to select the left pane
w j to select the pane below
w k to select the pane above
w l to select the right pane
There is also a sticky mode (w w) that enables h, j, k, l to select the panes as you want to, without a prefix key. Please see the repository for more information.

Tmux copy mode: how to create your own command?

I love Tmux and its copy mode with Vi commands, but I'm really annoyed by the fact that this mode is very far from being as efficient as real Vim.
For example, there is no keybinding to just copy a word (yw), I must always "go to the beginning of a word" "begin selection", "go to the end of the word" then "finish selection". A lot of operations when I just need to do yw in vim.
I searched a way to create my own "yw" command in Tmux copy mode. Chaining all the operations needed is a good idea, but a simple bind with commands separated by ; just doesn't work (similar thing works in non-copy mode). Is there something I miss? Or is the copy mode of Tmux just limited and not as scriptable as I need it to be?
I have this in my tmux conf:
# vi-style controls in copy mode
set-option -g status-keys vi
set-window-option -g mode-keys vi
# v and y like vi in copy-mode
bind-key -t vi-copy 'v' begin-selection
bind-key -t vi-copy 'y' copy-selection
Now after going copy-mode i can easily select words by:
vw
And copy with
y
In tmux you have to select something to copy. There is nothing like copying in normal mode as you know from usual vi/vim commands. Unfortunately you can only use one key (like v or y) for every tmux argument.
You can find more about tmux's vi movement commands here: https://superuser.com/a/197272/57890
This appears to be a bug in the bind-key command when called with the -t option. I have filed a bug report at https://sourceforge.net/tracker/?func=detail&aid=3533562&group_id=200378&atid=973262.
On upstream (2.4+) tmux version this got changed, in order to create a bindings for begin selection you need to use -T and send-keys with -X.
More info in tmux changelog.
Here my bindings for vi copy mode as an example:
# Bind `v` to trigger selection
bind-key -T copy-mode-vi v send-keys -X begin-selection
# Bind `y` to yank current selection
bind-key -T copy-mode-vi y send-keys -X copy-selection-and-cancel
# Rebind `mouse click + drag button release` to not jump away from context
bind-key -T copy-mode-vi MouseDragEnd1Pane send-keys -X copy-selection
If you are using emacs copy mode, replacing copy-mode-vi with copy-mode should be enough.
There's a patch for tmux allowing to create procedures and bind any number of actions for 'mode' keystrokes: http://ershov.github.io/tmux/

How do I make tmux reorder windows when one is deleted?

I have three windows:
1:zsh 2:vim* 3:htop
When I delete the current window (#2), I have these windows left:
1:zsh 3:htop
How can I make it so that it automatically renumbers them as
1:zsh 2:htop
If I recall correctly, this is the default behavior of GNU Screen. I know I could always :swap-window, but I would like to know if this is possible automatically.
Let's do it more simply.
If you are using tmux below version 1.7, append next line to ~/.tmux.conf:
bind-key C-s run "for i in $(tmux lsw|awk -F: '{print $1}'); do tmux movew -s \$i; done"
You could sort all windows, by typing PREFIX-KEY, then Ctrl + s.
Else, if you are using tmux version 1.7 or above, as already everybody says, append next line to ~/.tmux.conf:
set-option -g renumber-windows on
Since tmux 1.7, you can type just one command to do so:
tmux movew -r
This has now been implemented in C and submitted to tmux CVS on OpenBSD. Will hit the sourceforge portable release soon.
https://github.com/ThomasAdam/tmux-obsd/commit/c42e9b038dcdd36944e76954258a484387bd988f
The bash script below (updated version of [1] to reflect changes in tmux API) reorders tmux sessions. I suggest adding this as a bash function which you can call from any shell.
# re-number tmux sessions
for session in $(tmux ls | awk -F: '{print $1}') ;do
inum=0
for window in $(tmux lsw -t 0 | awk -F: '/^[0-9*]/ {print $1}') ;do
if [ ${window} -gt ${inum} ] ;then
echo "${session}:${window} -> ${session}:${inum}"
tmux movew -d -s ${session}:${window} -t ${session}:${inum}
fi
inum=$((${inum}+1))
done
done
[1] http://brainscraps.wikidot.com/tmux-renum

Resources