使用 tmux 打造更强大的终端
tmux 终端 命令行
![](/data/attachment/album/201704/19/001448kmij2jbwm8r82jib.jpg)


一些 Fedora 用户把大部分甚至是所有时间花费在了[命令行](http://www.cryptonomicon.com/beginning.html)终端上。 终端可让您访问整个系统，以及数以千计的强大的实用程序。 但是，它默认情况下一次只显示一个命令行会话。 即使有一个大的终端窗口，整个窗口也只会显示一个会话。 这浪费了空间，特别是在大型显示器和高分辨率的笔记本电脑屏幕上。 但是，如果你可以将终端分成多个会话呢？ 这正是 tmux 最方便的地方，或者说不可或缺的。


### 安装并启动 tmux


tmux 应用程序的名称来源于<ruby> 终端 <rp>  （ </rp> <rt>  terminal </rt> <rp>  ） </rp></ruby><ruby> 复用器 <rp>  （ </rp> <rt>  muxer </rt> <rp>  ） </rp></ruby>或<ruby> 多路复用器 <rp>  （ </rp> <rt>  multiplexer </rt> <rp>  ） </rp></ruby>。 换句话说，它可以将您的单终端会话分成多个会话。 它管理窗口和窗格：


* <ruby> 窗口 <rp>  （ </rp> <rt>  window </rt> <rp>  ） </rp></ruby>是一个单一的视图 - 也就是终端中显示的各种东西。
* <ruby> 窗格 <rp>  （ </rp> <rt>  pane </rt> <rp>  ） </rp></ruby>是该视图的一部分，通常是一个终端会话。


开始前，请在系统上安装 `tmux` 应用程序。 你需要为您的用户帐户设置 `sudo` 权限（如果需要，请[查看本文](https://fedoramagazine.org/howto-use-sudo/)获取相关说明）。



```
sudo dnf -y install tmux

```

运行 `tmux`程序：



```
tmux

```

### 状态栏


首先，似乎什么也没有发生，除了出现在终端的底部的状态栏：


![Start of tmux session](/data/attachment/album/201704/19/001448krty4z3p6k77yowf.png)


底部栏显示：


* `[0]` – 这是 `tmux` 服务器创建的第一个会话。编号从 0 开始。`tmux` 服务器会跟踪所有的会话确认其是否存活。
* `0:testuser@scarlett:~` – 有关该会话的第一个窗口的信息。编号从 0 开始。这表示窗口的活动窗格中的终端归主机名 `scarlett` 中 `testuser` 用户所有。当前目录是 `~` (家目录)。
* `*` – 显示你目前在此窗口中。
* `“scarlett.internal.fri”` – 你正在使用的 `tmux` 服务器的主机名。
* 此外，还会显示该特定主机上的日期和时间。


当你向会话中添加更多窗口和窗格时，信息栏将随之改变。


### tmux 基础知识


把你的终端窗口拉伸到最大。现在让我们尝试一些简单的命令来创建更多的窗格。默认情况下，所有的命令都以 `Ctrl+b` 开头。


* 敲 `Ctrl+b, "` 水平分割当前单个窗格。 现在窗口中有两个命令行窗格，一个在顶部，一个在底部。请注意，底部的新窗格是活动窗格。
* 敲 `Ctrl+b, %` 垂直分割当前单个窗格。 现在你的窗口中有三个命令行窗格，右下角的窗格是活动窗格。


![tmux window with three panes](/data/attachment/album/201704/19/001448nkfld9w393fp4gz9.png)


注意当前窗格周围高亮显示的边框。要浏览所有的窗格，请做以下操作：


* 敲 `Ctrl+b`，然后点箭头键
* 敲 `Ctrl+b, q`，数字会短暂的出现在窗格上。在这期间，你可以你想要浏览的窗格上对应的数字。


现在，尝试使用不同的窗格运行不同的命令。例如以下这样的：


* 在顶部窗格中使用 `ls` 命令显示目录内容。
* 在左下角的窗格中使用 `vi` 命令，编辑一个文本文件。
* 在右下角的窗格中运行 `top` 命令监控系统进程。


屏幕将会如下显示:


![tmux session with three panes running different commands](/data/attachment/album/201704/19/001449ndd2dvvk9xjdq3zx.png)


到目前为止，这个示例中只是用了一个带多个窗格的窗口。你也可以在会话中运行多个窗口。


* 为了创建一个新的窗口，请敲`Ctrl+b, c` 。请注意，状态栏显示当前有两个窗口正在运行。（敏锐的读者会看到上面的截图。）
* 要移动到上一个窗口，请敲 `Ctrl+b, p` 。
* 要移动到下一个窗口，请敲 `Ctrl+b, n` 。
* 要立即移动到特定的窗口，请敲 `Ctrl+b` 然后跟上窗口编号。


如果你想知道如何关闭窗格，只需要使用 `exit` 、`logout`，或者 `Ctrl+d` 来退出特定的命令行 shell。一旦你关闭了窗口中的所有窗格，那么该窗口也会消失。


### 脱离和附加


`tmux` 最强大的功能之一是能够脱离和重新附加到会话。 当你脱离的时候，你可以离开你的窗口和窗格独立运行。 此外，您甚至可以完全注销系统。 然后，您可以登录到同一个系统，重新附加到 `tmux` 会话，查看您离开时的所有窗口和窗格。 脱离的时候你运行的命令一直保持运行状态。


为了脱离一个会话，请敲 `Ctrl+b, d`。然后会话消失，你重新返回到一个标准的单一 shell。如果要重新附加到会话中，使用一下命令：



```
tmux attach-session

```

当你连接到主机的网络不稳定时，这个功能就像救生员一样有用。如果连接失败，会话中的所有的进程都会继续运行。只要连接恢复了，你就可以恢复正常，就好像什么事情也没有发生一样。


如果这些功能还不够，在每个会话的顶层窗口和窗格中，你可以运行多个会话。你可以列举出这些窗口和窗格，然后通过编号或者名称把他们附加到正确的会话中：



```
tmux list-sessions

```

### 延伸阅读


本文只触及的 `tmux` 的表面功能。你可以通过其他方式操作会话：


* 将一个窗格和另一个窗格交换
* 将窗格移动到另一个窗口中（可以在同一个会话中也可以在不同的会话中）
* 设定快捷键自动执行你喜欢的命令
* 在 `~/.tmux.conf` 文件中配置你最喜欢的配置项，这样每一个会话都会按照你喜欢的方式呈现


有关所有命令的完整说明，请查看以下参考：


* 官方[手册页](http://man.openbsd.org/OpenBSD-current/man1/tmux.1)
* `tmux` [电子书](https://pragprog.com/book/bhtmux2/tmux-2)




---


作者简介：


Paul W. Frields 自 1997 年以来一直是 Linux 用户和爱好者，并于 2003 年加入 Fedora 项目，这个项目刚推出不久。他是 Fedora 项目委员会的创始成员，在文档，网站发布，宣传，工具链开发和维护软件方面都有贡献。他于2008 年 2 月至 2010 年 7 月加入 Red Hat，担任 Fedora 项目负责人，并担任 Red Hat 的工程经理。目前他和妻子以及两个孩子居住在弗吉尼亚。




---


via: <https://fedoramagazine.org/use-tmux-more-powerful-terminal/>


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


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


OK
Some Fedora users spend most or all their time at a [command line](http://www.cryptonomicon.com/beginning.html) terminal. The terminal gives you access to your whole system, as well as thousands of powerful utilities. However, it only shows you one command line session at a time by default. Even with a large terminal window, the entire window only shows one session. This wastes space, especially on large monitors and high resolution laptop screens. But what if you could break up that terminal into multiple sessions? This is precisely where *tmux* is handy — some say indispensable.

## Install and start *tmux*

The *tmux* utility gets its name from being a terminal muxer, or multiplexer. In other words, it can break your single terminal session into multiple sessions. It manages both *windows* and *panes*:

- A
*window*is a single view — that is, an assortment of things shown in your terminal. - A
*pane*is one part of that view, often a terminal session.

To get started, install the *tmux* utility on your system. You’ll need to have *sudo* setup for your user account ([check out this article](https://fedoramagazine.org/howto-use-sudo/) for instructions if needed).

sudo dnf -y install tmux

Run the utility to get started:

tmux

## The status bar

At first, it might seem like nothing happens, other than a status bar that appears at the bottom of the terminal:


The bottom bar shows you:

*[0]*– You’re in the first session that was created by the*tmux*server. Numbering starts with 0. The server tracks all sessions whether they’re still alive or not.*0:username@host:~*– Information about the first window of that session. Numbering starts with 0. The terminal in the active pane of the window is owned by*username*at hostname*host*. The current directory is*~*(the home directory).***– Shows that you’re currently in this window.*“hostname”*– the hostname of the*tmux*server you’re using.- Also, the date and time on that particular host is shown.

The information bar will change as you add more windows and panes to the session.

## Basics of tmux

Stretch your terminal window to make it much larger. Now let’s experiment with a few simple commands to create additional panes. All commands by default start with *Ctrl+b*.

- Hit
*Ctrl+b, “*to split the current single pane horizontally. Now you have two command line panes in the window, one on top and one on bottom. Notice that the new bottom pane is your active pane. - Hit
*Ctrl+b, %*to split the current pane vertically. Now you have three command line panes in the window. The new bottom right pane is your active pane.

Notice the highlighted border around your current pane. To navigate around panes, do any of the following:

- Hit
*Ctrl+b*and then an arrow key. - Hit
*Ctrl+b, q*. Numbers appear on the panes briefly. During this time, you can hit the number for the pane you want.

Now, try using the panes to run different commands. For instance, try this:

- Use
*ls*to show directory contents in the top pane. - Start
*vi*in the bottom left pane to edit a text file. - Run
*top*in the bottom right pane to monitor processes on your system.

The display will look something like this:

So far, this example has only used one window with multiple panes. You can also run multiple windows in your session.

- To create a new window, hit
*Ctrl+b, c.*Notice that the status bar now shows two windows running. (Keen readers will see this in the screenshot above.) - To move to the previous window, hit
*Ctrl+b, p.* - If you want to move to the next window, hit
*Ctrl+b, n*. - To immediately move to a specific window (0-9), hit
*Ctrl+b*followed by the window number.

If you’re wondering how to close a pane, simply quit that specific command line shell using *exit*, *logout*, or *Ctrl+d.* Once you close all panes in a window, that window disappears as well.

## Detaching and attaching

One of the most powerful features of *tmux* is the ability to detach and reattach to a session. You can leave your windows and panes running when you detach. Moreover, you can even logout of the system entirely. Then later you can login to the same system, reattach to the *tmux* session, and see all your windows and panes where you left them. The commands you were running stay running while you’re detached.

To detach from a session, hit *Ctrl+b, d.* The session disappears and you’ll be back at the standard single shell. To reattach to the session, use this command:

tmux attach-session

This function is also a lifesaver when your network connection to a host is shaky. If your connection fails, all the processes in the session will stay running. Once your connection is back up, you can resume your work as if nothing happened.

And if that weren’t enough, on top of multiple windows and panes per session, you can also run multiple sessions. You can list these and then attach to the correct one by number or name:

tmux list-sessions

## Further reading

This article only scratches the surface of *tmux’*s capabilities. You can manipulate your sessions in many other ways:

- Swap one pane with another
- Move a pane to another window (in the same or a different session!)
- Set keybindings that perform your favorite commands automatically
- Configure a
*~/.tmux.conf*file with your favorite settings by default so each new session looks the way you like

For a full explanation of all commands, check out these references:

- The official
[manual page](http://man.openbsd.org/OpenBSD-current/man1/tmux.1) - This
[eBook](https://pragprog.com/book/bhtmux2/tmux-2)all about*tmux*

## wk3

Cool information! I had never run across

before. I can think of several situations in the past where it would have saved a lot of time and frustration. Thanks!

## Steven

I use tmux and powerline together as my terminal choice. It makes for an efficient terminal experience.

## wigust

Also try out byobu package for better defaults.

## kapoath

Can i run specific panes or even windows as root, while others not?

Due to scripts running under root.

## Braxton Plaxco

If you start a session under a certain user, then new windows and panes will, by default, be under that user, but yes you can run a process as root using sudo or su in a window or pane with the others staying unaffected.

## GMaster

Yes, that’s definitely possible.

## Xplosm

Yes you can! They are all independent TTY sessions!

## Daniel

Kind of. You run tmux as root, and su to your other user in the panes you want. Or the other way around. Think about the security implications though,

## MG

Nothing stops you to switch to whatever user you need in any pane. Or use sudo. Whatever you can do in a shell.

## twoCore

You can start tmux as a “normal” user and run “su -” in a specific pane / window. So you can run scripts under root in the pane ( sorry for my english ). I use tmux for years to connect to multiple servers ( each pane has it own ssh connection ), which is very cool.

## Kyle R. Conway

Yes you can. Different panels within tmux can be root and non-root (or even ssh’d into other machines as other users). Very powerful tool.

## chandan

One of the features that I rely on is the fact that tmux is scriptable. Just typing a key combination will setup the dev & test environment within appropriate panes.

## RTG

I tried it and like it. I’m always looking for new ways to increase efficiency while at the term. Currently use ansi-term from within emacs where I too can split windows, create multiple sessions and more. But tmux is something I can also use and recommend to others. Thanks!

## Tzvetan

Hallo ,

I don’t know why but the Ctrl+b is not working for me . Thanks

Linux samurai 4.8.13-100.fc23.x86_64 #1 SMP Fri Dec 9 14:51:40 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

## MichaelC

@kapoath

Each pane is a new shell instance, so this an absolute yes.

You can also create preconfigured sessions with panes in the size you need them.

## dminsky

Thanks for article! Always want to know what is the difference between tmux and screen. Still doesn’t know, but at least I’ve tried tmux 😉

## Andrey Motoshkov

Very useful (for myself at least) Ctrl-b,z: zoom-in/out the pane (make pane fullscreen and then back to previous size)

## Anon

I think a Window manager like i3 does this better

## André Luís de Andrade Mendes

Which is better, tmux or screen ?

## Paul W. Frields

@André: It’s not really a matter of better/worse, although I think tmux may have the edge on features. But tmux is also actively maintained, and I believe screen, although stable, is not really updated regularly these days. On that basis I would recommend tmux.

## mahetz

I just use screen all the day, it does what i need, e.x. create a new named detached session with a script.

But what I`m really missing is to capture a terminal started with a ssh login into a session, which a can detach.

Can tmux do this, and most important, reliable?

## Nicolas

Why not using Terminator instead? What are the pros about Tmux? Thanks!

## John Holmes

Since you can detach and reattach to a tmux session, it works incredibly well for remote terminal access. If your network connection drops or you need to reboot your local machine, you can pickup where you left off just by reconnecting and typing “tmux attach”. Terminator is amazing, but to me, this is tmux’s killer feature.

## Peeved Off

my keybindings don’t work

The only thing that works for me is:

Ctl+b, ”

And it doesnt behave as expected. It asks me for a index value for the window to switch to and since I have only one window it fails unless I add 0

I tried adding a local conf file and rebinding to Ctl+C but same result.

I even went through systematically using keys with the bind key and most didn’t work and none mapped to the documentation.

I am running F25 with Wayland

Arrrg.

## Paul W. Frields

@Peeved: I’m also running on F25 Workstation with Wayland so I can testify that tmux works fine. Try duplicating the issue on a brand new user account, and/or a fresh installation. It’s possible certain keyboard models or configurations could interfere with proper operation. Also, some non-standard desktop environments may have keybindings that interfere with tmux. Please use community help channels for more support, as this is not a support forum: https://fedoraproject.org/wiki/Communicating_and_getting_help

## Kyew

For those who said i3 Window Manager or Terminator does a better job, you’re missing an important point. tmux works in within your terminal session, can continue running in the background, and was primarily made for remote sessions. You can start a tmux session, start a long running process in it, “disconnect” and then come back to it later. This works great if your connected via ssh to a server. You can run tmux, do your work, and if the connection drops you can re-establish your ssh session and then reconnect to the tmux session you dropped from. Whatever you were doing is still sitting there waiting for you to return.

Another program called “screen” does pretty much the same thing.

## Jesse Vas

Reminds me of Glenda. I like it!

## Kevin

How can I get tmux to automatically start when I start my terminal.

## Paul W. Frields

@Kevin: You can usually set a command to run for each terminal in the settings for your terminal app. In the Fedora Workstation’s Terminal app, you can find this by editing the Profile (right click the Terminal or choose it from the app menu on the GNOME Shell menu bar). Edit the profile, choose Command, and use a custom command ‘tmux’.

## Braxton Plaxco

This is what I use. Then I use tmux windows instead of tabs or different terminals.

I have this in my bashrc

Tmux Setup

if [ -z “$TMUX” ]

then

tmux new-session -As default

fi