2021-09-20 Simple tmux scripting

I have recently started to use tmux instead of separate tabs in my terminal. I had a few reasons for this, one of them being that tmux is much more keyboard-oriented. (Actually, one reason not to use tmux could be that it’s not Emacs-based, and it’s keybindings are very non-Emacsy. I could probably use multiple Eshell windows instead of it, but I am somehow not totally convinced to Eshell.) Also, I can easily split my window into two panes, which I like quite a lot. Word of warning: it seems a better idea to split it into “top” and “bottom” panes with C-b " than to “left” and “right” ones with C-b %. Even if the leftright variant is more efficient in terms of screen space, it makes copying multiline strings using the mouse very/ inconvenient, since – from the point of view of the terminal application – a line spans both panes then.

One of the bigger reasons for using tmux is that it can be easily scripted. For instance, I usually opened 3 terminal tabs at the beginning of the day, and entered specific commands in every one of them – the same ones every day. With tmux, I could write a script to do the same. For example, here is a slightly simplified version of my current bash script I can run in the morning:

tmux new -s work -d
tmux rename-window -t work logs
tmux send-keys -t work 'cd $BASE_DIR && vagrant up && vagrant ssh' C-m 'pm2 log' C-m
tmux new-window -t work
tmux rename-window -t work vm
tmux send-keys -t work 'cd $BASE_DIR && sleep 36 && vagrant ssh' C-m
tmux new-window -t work
tmux rename-window -t work term
tmux send-keys -t work 'cd $BASE_DIR && git pull' C-m
tmux attach -t work

(I changed the actual commands so that they don’t contain the actual names of directories etc.) Note that the first window starts the virtual machine, ssh’s into it and starts pm2 logs inside.

One thing I’m not quite satisfied with is the sleep 36 part. I found by experimenting a bit that this is enough to make sure the virtual machine is up and running, but of course this is a very crude solution. After skimming through the internet (especially answers to this SO question) and tmux manpage (which seems to be pretty extensive), I am fairly sure that it is possible to make tmux run a command when some text is displayed in a chosen window. For now, I will use the sleep variant, but I will defnitely be researching a better idea.

CategoryEnglish, CategoryBlog, CategoryEmacs