user9007131
user9007131

Reputation: 29

Why does my shell script for creating a split-window tmux session not work

I am on macOS and using zsh. I have created a folder ~/bin/ which I've added to my path. I created a shell script ~/bin/testscript containing the following code

#!/bin/sh
tmux new-session -s testsession
tmux split-window -v

and used chmod -R 700 ~/bin to set the permissions -rwx------.

When executing the lines from the shell script successively by typing them in the shell I get a new tmux session with vertically split windows. This is the expected behavior. However, when I type testscript into the shell I only get a new tmux session, but without vertically split windows.

What do I need to do to change in the script to get a session with split windows? I've copied the above code from this thread, but it doesn't work for me.

Upvotes: 0

Views: 1238

Answers (2)

William Pursell
William Pursell

Reputation: 212584

When you run those command manually, you are typing the 2nd line in a shell running in the new session. When you run the script, the 2nd line is not executing inside that session. Try:

tmux new-session -s testsession "$SHELL" \; split-window -v

or

#!/bin/bash

tmux new-session -d -s testsession
tmux split-window -v -t testsession:0.0
tmux attach-session -t testsession

Upvotes: 2

chepner
chepner

Reputation: 532238

You get a new session, and you immediately attach to that session. This causes the first call to tmux to block until you detach from that session, preventing the script from preceding to the second call to tmux.

To prevent that, create the new session without attaching to it immediately by using the -d option. Once you've used split-window to create the second pane, then you can attach to the session.

#!/bin/sh
tmux new-session -d -s testsession
tmux split-window -v -t testsession
tmux attach -t testsession

split-window's -t option technically takes a window, not a session, but as the new session only has one window, it defaults to that window.

tmux attach, with no -t option, will attach to the most recently used session, so -t testsession can be considered optional here.

Upvotes: 1

Related Questions