更好利用 tmux 会话的 4 个技巧
tmux
![](/data/attachment/album/201810/07/204525twecrrews57jngs6.jpg)


tmux 是一个终端多路复用工具，它可以让你系统上的终端支持多面板。你可以排列面板位置，在每个面板运行不同进程，这通常可以更好的地利用你的屏幕。我们在 [这篇早期的文章](https://fedoramagazine.org/use-tmux-more-powerful-terminal/) 中向读者介绍过这一强力工具。如果你已经开始使用 tmux 了，那么这里有一些技巧可以帮你更好地使用它。


本文假设你当前的前缀键是 `Ctrl+b`。如果你已重新映射该前缀，只需在相应位置替换为你定义的前缀即可。


### 设置终端为自动使用 tmux


使用 tmux 的一个最大好处就是可以随意的从会话中断开和重连。这使得远程登录会话功能更加强大。你有没有遇到过丢失了与远程系统的连接，然后好希望能够恢复在远程系统上做过的那些工作的情况？tmux 能够解决这一问题。


然而，有时在远程系统上工作时，你可能会忘记开启会话。避免出现这一情况的一个方法就是每次通过交互式 shell 登录系统时都让 tmux 启动或附加上一个会话。


在你远程系统上的 `~/.bash_profile` 文件中加入下面内容：



```
if [ -z "$TMUX" ]; then
    tmux attach -t default || tmux new -s default
fi
```

然后注销远程系统，并使用 SSH 重新登录。你会发现你处在一个名为 `default` 的 tmux 会话中了。如果退出该会话，则下次登录时还会重新生成此会话。但更重要的是，若您正常地从会话中分离，那么下次登录时你会发现之前工作并没有丢失 - 这在连接中断时非常有用。


你当然也可以将这段配置加入本地系统中。需要注意的是，大多数 GUI 界面的终端并不会自动使用这个 `default` 会话，因此它们并不是登录 shell。虽然你可以修改这一行为，但它可能会导致终端嵌套执行附加到 tmux 会话这一动作，从而导致会话不太可用，因此当进行此操作时请一定小心。


### 使用缩放功能使注意力专注于单个进程


虽然 tmux 的目的就是在单个会话中提供多窗口、多面板和多进程的能力，但有时候你需要专注。如果你正在与一个进程进行交互并且需要更多空间，或需要专注于某个任务，则可以使用缩放命令。该命令会将当前面板扩展，占据整个当前窗口的空间。


缩放在其他情况下也很有用。比如，想象你在图形桌面上运行一个终端窗口。面板会使得从 tmux 会话中拷贝和粘帖多行内容变得相对困难。但若你缩放了面板，就可以很容易地对多行数据进行拷贝/粘帖。


要对当前面板进行缩放，按下 `Ctrl+b, z`。需要恢复的话，按下相同按键组合来恢复面板。


### 绑定一些有用的命令


tmux 默认有大量的命令可用。但将一些更常用的操作绑定到容易记忆的快捷键会很有用。下面一些例子可以让会话变得更好用，你可以添加到 `~/.tmux.conf` 文件中：



```
bind r source-file ~/.tmux.conf \; display "Reloaded config"
```

该命令重新读取你配置文件中的命令和键绑定。添加该条绑定后，退出任意一个 tmux 会话然后重启一个会话。现在你做了任何更改后，只需要简单的按下 `Ctrl+b, r` 就能将修改的内容应用到现有的会话中了。



```
bind V split-window -h
bind H split-window
```

这些命令可以很方便地对窗口进行横向切分（按下 `Shift+V`）和纵向切分（`Shift+H`）。


若你想查看所有绑定的快捷键，按下 `Ctrl+B, ?` 可以看到一个列表。你首先看到的应该是复制模式下的快捷键绑定，表示的是当你在 tmux 中进行复制粘帖时对应的快捷键。你添加的那两个键绑定会在<ruby> 前缀模式 <rt>  prefix mode </rt></ruby>中看到。请随意把玩吧！


### 使用 powerline 更清晰


[如前文所示](https://fedoramagazine.org/add-power-terminal-powerline/)，powerline 工具是对 shell 的绝佳补充。而且它也兼容在 tmux 中使用。由于 tmux 接管了整个终端空间，powerline 窗口能提供的可不仅仅是更好的 shell 提示那么简单。


[![Screenshot of tmux powerline in git folder](/data/attachment/album/201810/07/204536rfa6vuar6laca60l.png)](https://fedoramagazine.org/wp-content/uploads/2018/08/Screenshot-from-2018-08-25-19-36-53.png)


如果你还没有这么做，按照 [这篇文章](https://fedoramagazine.org/add-power-terminal-powerline/) 中的指示来安装该工具。然后[使用 sudo](https://fedoramagazine.org/howto-use-sudo/) 来安装附件：



```
sudo dnf install tmux-powerline
```

接着重启会话，就会在底部看到一个漂亮的新状态栏。根据终端的宽度，默认的状态栏会显示你当前会话 ID、打开的窗口、系统信息、日期和时间，以及主机名。若你进入了使用 git 进行版本控制的项目目录中还能看到分支名和用色彩标注的版本库状态。


当然，这个状态栏具有很好的可配置性。享受你新增强的 tmux 会话吧，玩的开心点。




---


via: <https://fedoramagazine.org/4-tips-better-tmux-sessions/>


作者：[Paul W. Frields](https://fedoramagazine.org/author/pfrields/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[lujun9972](https://github.com/lujun9972) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
The tmux utility, a terminal multiplexer, lets you treat your terminal as a multi-paned window into your system. You can arrange the configuration, run different processes in each, and generally make better use of your screen. We introduced some readers to this powerful tool [in this earlier article](https://fedoramagazine.org/use-tmux-more-powerful-terminal/). Here are some tips that will help you get more out of tmux if you’re getting started.


This article assumes your current prefix key is **Ctrl+b**. If you’ve remapped that prefix, simply substitute your prefix in its place.

## Set your terminal to automatically use tmux

One of the biggest benefits of tmux is being able to disconnect and reconnect to sesions at wilI. This makes remote login sessions more powerful. Have you ever lost a connection and wished you could get back the work you were doing on the remote system? With tmux this problem is solved.

However, you may sometimes find yourself doing work on a remote system, and realize you didn’t start a session. One way to avoid this is to have tmux start or attach every time you login to a system with in interactive shell.

Add this to your remote system’s *~/.bash_profile* file:

if [ -z "$TMUX" ]; then tmux attach -t default || tmux new -s default fi

Then logout of the remote system, and log back in with SSH. You’ll find you’re in a tmux session named *default.* This session will be regenerated at next login if you exit it. But more importantly, if you detach from it as normal, your work is waiting for you next time you login — especially useful if your connection is interrupted.

Of course you can add this to your local system as well. Note that terminals inside most GUIs won’t use the default session automatically, because they aren’t login shells. While you can change that behavior, it may result in nesting that makes the session less usable, so proceed with caution.

## Use zoom to focus on a single process

While the point of tmux is to offer multiple windows, panes, and processes in a single session, sometimes you need to focus. If you’re in a process and need more space, or to focus on a single task, the zoom command works well. It expands the current pane to take up the entire current window space.

Zoom can be useful in other situations too. For instance, imagine you’re using a terminal window in a graphical desktop. Panes can make it harder to copy and paste multiple lines from inside your tmux session. If you zoom the pane, you can do a clean copy/paste of multiple lines of data with ease.

To zoom into the current pane, hit **Ctrl+b, z**. When you’re finished with the zoom function, hit the same key combo to unzoom the pane.

## Bind some useful commands

By default tmux has numerous commands available. But it’s helpful to have some of the more common operations bound to keys you can easily remember. Here are some examples you can add to your *~/.tmux.conf* file to make sessions more enjoyable:

bind r source-file ~/.tmux.conf \; display "Reloaded config"

This command rereads the commands and bindings in your config file. Once you add this binding, exit any tmux sessions and then restart one. Now after you make any other future changes, simply run **Ctrl+b, r** and the changes will be part of your existing session.

bind V split-window -h bind H split-window

These commands make it easier to split the current window across a vertical axis (note that’s **Shift+V**) or across a horizontal axis (**Shift+H**).

If you want to see how all keys are bound, use **Ctrl+B, ?** to see a list. You may see keys bound in *copy-mode* first, for when you’re working with copy and paste inside tmux. The *prefix* mode bindings are where you’ll see ones you’ve added above. Feel free to experiment with your own!

## Use powerline for great justice

[As reported in a previous Fedora Magazine article](https://fedoramagazine.org/add-power-terminal-powerline/), the *powerline* utility is a fantastic addition to your shell. But it also has capabilities when used with tmux. Because tmux takes over the entire terminal space, the powerline window can provide more than just a better shell prompt.

If you haven’t already, follow the instructions in the [Magazine’s powerline article](https://fedoramagazine.org/add-power-terminal-powerline/) to install that utility. Then, install the addon [using sudo](https://fedoramagazine.org/howto-use-sudo/):

sudo dnf install tmux-powerline

Now restart your session, and you’ll see a spiffy new status line at the bottom. Depending on the terminal width, the default status line now shows your current session ID, open windows, system information, date and time, and hostname. If you change directory into a git-controlled project, you’ll see the branch and color-coded status as well.

Of course, this status bar is highly configurable as well. Enjoy your new supercharged tmux session, and have fun experimenting with it.

Photo by [Pamela Saunders](https://unsplash.com/photos/S-Med_LVdio?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/search/photos/window?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText).

## dac.override

Tmux is great especially if you do not have access to a GUI, and these are great tips for making the experience better.

But it does to me also make a good point. By default traditional terminal multiplexers do not integrate as well as they could. There are some downsides to using it . For example nesting TMUX instances, but also its unawareness of SSH and a terminal emulator if applicable.

TermySequence Termy-server is a “TMUX” server implementation and TermySequence Qtermy is a QT client implementation that works alone and with Termy-server. Qtermy is a modern terminal emulator that leverages SSH as well as termy-server.

The downside of TermySequence compared to TMUX is that you need a GUI-client (Qtermy is a reference implementation of that). So it is not a solution for the command line. The benefit of TermySequence is that you get a more integrated and modern experience.

It is available on COPR:

https://copr.fedorainfracloud.org/coprs/ewalsh/termysequence/

Website:

https://termysequence.io/

## Pieter

Thanks Paul. Setting my terminal to automatically use tmux is a great tip. For splitting a window I use shift+| and shift+_ but I definitely like your H for the horizontal axis and V for the vertical axis. Should you ever consider a follow up article on tmux then please include how to setup copy and paste across vim instances in tmux as that seems to have many folks puzzled.

## Mace Moneta

Even better, use a ssh-mosh client to connect. It establishes connections via SSH, then uses encrypted UDP and maintains connections even across sleep, switching access points, or hopping between WiFi and LTE and back again. There are clients for ChromeOS:

https://chrome.google.com/webstore/detail/mosh/ooiklbnjmhbcgemelgfhaeaocllobloj

and Android as well:

https://play.google.com/store/apps/details?id=com.server.auditor.ssh.client

In combination with tmux or screen, it allows me to maintain continuous connections to our servers.

## Andreas

And if you haven’t discovered it yet.

There is tmate for pair-programming!

## Demetrius Veras

nice

## Tomas

You can also use tmux-top in your status to get some handy info about the host. It’s in Fedora repos.

https://github.com/TomasTomecek/tmux-top

## Chiqo

TIL the zoom feature, thank you.

My status bar now looks like:

set-window-option -g window-status-current-format “#[bg=white]#[fg=colour166]| #I.#{?window_zoomed_flag,#[bg=colour166]#[fg=white],}#P#[bg=white]#[fg=colour166]:#W |”

## Kyle R. Conway

Paul,

Had no idea you could use this is tmux. I’ve got this in my ~/.tmux.conf but I’m not seeing powerline function after installing tmux-powerline. Any ideas?

powerline_tmux_1.8.conf

tmux Version 1.8 introduces window-status-last-{attr,bg,fg}, which is

deprecated for versions 1.9+, thus only applicable to version 1.8.

set -qg window-status-last-fg “$_POWERLINE_ACTIVE_WINDOW_FG”

vim: ft=tmux

source “/usr/share/tmux/powerline.conf”

## Steve

Hello Kyle,

There is a link mentioned above for an excellent article on setting up powerline. I personally don’t use tmux, preferring Terminal simply because that’s the first tabbed terminal I chose to use. Also, I am using zsh for my shell and the configuration file powerline in my case is therefore powerline.zsh, and can be found in /usr/share/powerline/zsh/

## Stephan

Thanks for sharing. Really great. I just get to know the Zoom thing. Really Cool

## Pierpaolo

As an alternative to Powerline, you can just add a few lines to your

to match the look of the popular Agnoster theme for Zsh https://github.com/i5ar/tmux-colors-solarized/blob/master/tmuxcolors-dark.conf

## juanfgs

But then all our shell will belong to us (not to mention that it will move every single zig)