简体   繁体   中英

tmux: run command in pane and capture result, in bash script

Using tmux, I'd like to run a command from one pane against another pane, and capture the output of the command.

For example, say in pane 7 I have an SSH session running, and I'd like to run a bash script in pane 2 to capture the host name from pane 7.

Is this possible?

I know I can do the send keys like so

$ tmux send-keys -t 7 "hostname" Enter

but I'm not sure how to capture the output from pane 7 into a bash variable.

I don't mind if it displays on the screen either (doesnt have to happen in the background).

EDIT: Note that hostname is just an example - I would like to run other scripts against each pane as well

As an alternative to capture-pane you can similarly use pipe-pane . It is often used for logging. You give it a command to pipe all output into, or no command at all to stop piping. So you end up with something like

tmux pipe-pane -t 7 'cat >/tmp/capture'
tmux send-keys -t 7 'hostname' Enter
sleep 1
tmux pipe-pane -t 7    # stops piping 
IT=$(</tmp/capture)

Beware, this capture includes carriage-return characters. You will need to remove the first and last lines of the capture to get just the wanted output. Eg:

IT=$(sed '1d;$d;s/\r//' </tmp/capture)

While not exactly what I was looking for, the tmux capture-pane command seems to capture the displayed output of a pane, which I can run of course after running my command.

example.sh

#/bin/bash

# run the command in another pane
tmux send-keys -t 7 "hostname" Enter

# capture it's output
IT=$(tmux capture-pane -p -t 7)
echo "$IT"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM