How to split a new window and run a command in this new window using tmux?

I have tried

tmux -c "shell command" split-window

but it does not seem to work.

Using tmux split-window, one can split a new window.

UPDATE:

Using tmux split-window 'exec ping g.cn' can run the ping command , but when stoped the new window will be closed.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use:

tmux split-window "shell command"

The split-window command has the following syntax:

 split-window [-dhvP] [-c start-directory] [-l size | -p percentage] [-t
         target-pane] [shell-command] [-F format]

(from man tmux, section “Windows and Panes”). Note that the order is important – the command has to come after any of those preceding options that appear, and it has to be a single argument, so you need to quote it if it has spaces.


For commands like ping -c that terminate quickly, you can set the remain-on-exit option first:

tmux set-option remain-on-exit on
tmux split-window 'ping -c 3 127.0.0.1'

The pane will remain open after ping finishes, but be marked “dead” until you close it manually.

If you don’t want to change the overall options, there is another approach. The command is run with sh -c, and you can exploit that to make the window stay alive at the end:

tmux split-window 'ping -c 3 127.0.0.1 ; read'

Here you use the shell read command to wait for a user-input newline after the main command has finished. In this case, the command output will remain until you press Enter in the pane, and then it will automatically close.

Method 2

bash --rcfile

This technique opens a new shell, runs commands, and leaves you there after the commands finish:

tmux-split-cmd() ( tmux split-window -dh -t $TMUX_PANE "bash --rcfile <(echo '. ~/.bashrc;$*')" )
tmux-split-cmd 'cd; pwd; ping google.com'

Or if the command has no special terminal characters like ; just:

tmux-split-cmd ping google.com

This uses:

Another interesting variant is:

tmux-split-cmd-uniq() (
  if [ "$(tmux list-panes | wc -l | cut -d' ' -f1)" -ne 1 ]; then
    tmux kill-pane -t 1
  fi
  tms "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e5a3e">[email protected]</a>"
)

which kills the previous split if it already exists, and helps to keep only one extra split at all times.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x