<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>linux知识 &#8211; bhzhuOS爱好者(原StartOS爱好者)</title>
	<atom:link href="https://www.bhzhu203.com/category/linux%E7%9F%A5%E8%AF%86/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.bhzhu203.com</link>
	<description>QQ群号125732839</description>
	<lastBuildDate>Wed, 18 Jun 2025 09:26:26 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.5.7</generator>
	<item>
		<title>如何将一个正在运行的任务挂载到 tmux 或者 screen 当中？</title>
		<link>https://www.bhzhu203.com/2025/06/18/%e5%a6%82%e4%bd%95%e5%b0%86%e4%b8%80%e4%b8%aa%e6%ad%a3%e5%9c%a8%e8%bf%90%e8%a1%8c%e7%9a%84%e4%bb%bb%e5%8a%a1%e6%8c%82%e8%bd%bd%e5%88%b0-tmux-%e6%88%96%e8%80%85-screen-%e5%bd%93%e4%b8%ad%ef%bc%9f/</link>
		
		<dc:creator><![CDATA[bhzhu203]]></dc:creator>
		<pubDate>Wed, 18 Jun 2025 09:26:26 +0000</pubDate>
				<category><![CDATA[Linux技巧]]></category>
		<category><![CDATA[reptyr]]></category>
		<category><![CDATA[tmux]]></category>
		<category><![CDATA[会话]]></category>
		<guid isPermaLink="false">https://www.bhzhu203.com/?p=488</guid>

					<description><![CDATA[将一个已经在运行的任务附加到 tmux 或 screen 会话中，通常需要一些技 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>将一个已经在运行的任务附加到 tmux 或 screen 会话中，通常需要一些技巧，因为这两个工具主要是设计用来在启动时就开始管理你的进程。然而，你可以通过以下方法来实现这一目标：</p>



<h2 class="wp-block-heading">使用 tmux</h2>



<pre class="wp-block-code"><code>初始化一个新的 tmux 会话： 如果你还没有在一个 tmux 会话中，首先你需要创建一个新的会话。


```bash
tmux new -s mysession
```

使用 reptyr 工具： 要将一个已经运行的进程转移到 tmux 会话中，可以使用 reptyr 工具。首先你需要安装 reptyr（具体安装命令视你的操作系统而定）。然后，在 tmux 会话中执行如下命令来“劫持”某个进程：


```bash
reptyr &lt;pid&gt;
```

其中 `&lt;pid&gt;` 是你想转移的那个进程的进程ID。</code></pre>



<h2 class="wp-block-heading">使用 screen</h2>



<p>虽然 screen 没有直接支持类似 reptyr 的功能，但你可以利用一个叫做 screen 的特性，称为“多窗口”模式，结合一些技巧来实现这一点。</p>



<pre class="wp-block-code"><code>创建一个新的 screen 会话：


```bash
screen -S mysession
```

准备进行进程迁移： 首先，找到你想转移的进程的 PID。然后，暂停该进程（如果你有权限的话），例如通过发送 SIGSTOP 信号：


```bash
kill -STOP &lt;pid&gt;
```

使用 gdb 来重新设置进程的控制终端： 这一步比较复杂，而且可能不总是有效，取决于系统和进程类型。基本思路是使用 gdb 附加到这个进程上，并调用 signal(SIGCONT) 来恢复它，同时改变它的控制终端到 screen 会话中。这通常涉及复杂的 gdb 命令操作，并且超出了简单的教程范围。

恢复进程： 如果你成功地改变了进程的控制终端，你可以在 screen 会话中继续运行该进程：


```bash
kill -CONT &lt;pid&gt;
```</code></pre>



<p>请注意，上述方法可能会因系统配置、权限以及特定进程的行为而有所不同。对于 screen 方法尤其如此，它可能并不适用于所有情况。使用 reptyr 是相对更简单也更可靠的选择，尤其是当你想要将任务转移到 tmux 或者新的 screen 会话中时。确保你在尝试这些操作前了解其风险，并备份重要数据。</p>



<h2 class="wp-block-heading">代码模式</h2>



<p>screen 也能用 reptyr 吗</p>



<p>是的，reptyr 也可以在 screen 会话中使用，以将已经运行的任务附加到 screen 会话里。尽管 screen 自身没有直接提供类似的功能，但通过 reptyr 工具，你可以实现在 screen 会话中接管其他终端上正在运行的程序。</p>



<p>这里是如何操作的基本步骤：</p>



<pre class="wp-block-code"><code>启动一个 screen 会话： 如果你还没有在一个 screen 会话中，请先启动一个新的会话。


```bash
screen -S mysession
```

找到你想转移的进程的 PID： 使用 ps, top, 或者其他任何工具来找到你想转移的那个进程的 PID。

暂停目标进程（如果需要）： 在某些情况下，你可能需要先暂停目标进程，以便能够成功地使用 reptyr 进行接管。


```bash
kill -STOP &lt;pid&gt;
```

其中 `&lt;pid&gt;` 是你的目标进程的 PID。

使用 reptyr 接管进程： 现在，在你的 screen 会话中运行 reptyr 并带上目标进程的 PID 来接管它。


```bash
reptyr &lt;pid&gt;
```

恢复进程（如果之前被暂停）： 如果你在第3步暂停了该进程，现在可以通过发送 SIGCONT 信号来恢复它。


```bash
kill -CONT &lt;pid&gt;
```</code></pre>



<p>需要注意的是，虽然这种方法通常有效，但它可能会因为系统配置、权限设置以及特定进程的行为而有所不同。此外，进行这些操作时应该小心，确保你了解所有相关风险，并考虑备份重要数据以防万一。在大多数情况下，reptyr 提供了一个相对简单且强大的方法来将任务从一个终端转移到另一个，包括 tmux 和 screen 会话。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>静态编译Python3程序模块指南- How to make Python3 static modules built-in , instead dynamic loading</title>
		<link>https://www.bhzhu203.com/2025/06/17/%e9%9d%99%e6%80%81%e7%bc%96%e8%af%91python3%e7%a8%8b%e5%ba%8f%e6%a8%a1%e5%9d%97%e6%8c%87%e5%8d%97-how-to-make-python3-static-modules-built-in-instead-dynamic-loading/</link>
		
		<dc:creator><![CDATA[bhzhu203]]></dc:creator>
		<pubDate>Tue, 17 Jun 2025 09:28:08 +0000</pubDate>
				<category><![CDATA[源码编译]]></category>
		<category><![CDATA[模块]]></category>
		<category><![CDATA[编译]]></category>
		<category><![CDATA[静态]]></category>
		<guid isPermaLink="false">https://www.bhzhu203.com/?p=486</guid>

					<description><![CDATA[静态编译的Python3程序可以不依赖发行版库文件环境，几乎可以在任何发行版零依 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>静态编译的Python3程序可以不依赖发行版库文件环境，几乎可以在任何发行版零依赖运行。</p>



<h2 class="wp-block-heading">构建静态Python3的方法</h2>



<h3 class="wp-block-heading">前提条件</h3>



<p>建议在 <strong>Alpine Linux 的 Docker</strong> 中编译</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">步骤说明</h2>



<h3 class="wp-block-heading">1. 确定静态编译模块</h3>



<p>首先确定要静态编译进Python的模块，比如需要将 <code>asyncio</code> 模块静态编译到 python3，而 <code>asyncio</code> 会依赖其它的底层模块（<code>_socket</code>，<code>math</code>，<code>select</code>，<code>array</code>，<code>_posixsubprocess</code>，<code>_contextvars</code> 等），详细的官方库编译项可以在 <code>Modules/Setup</code> 中查找，需要一次次尝试查漏补缺。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h3 class="wp-block-heading">2. 恢复源码目录初始状态</h3>



<pre class="wp-block-code"><code>make distclean</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h3 class="wp-block-heading">3. 编写静态编译模块配置文件</h3>



<p>将需要静态编译的模块信息写到文件 <code>Modules/Setup.local</code> 中：</p>



<pre class="wp-block-code"><code>vi Modules/Setup.local</code></pre>



<p>内容如下：</p>



<pre class="wp-block-code"><code>*static*
_asyncio _asynciomodule.c
_socket socketmodule.c
math mathmodule.c _math.c -DPy_BUILD_CORE_MODULE
select selectmodule.c
array arraymodule.c
_posixsubprocess _posixsubprocess.c
_contextvars _contextvarsmodule.c
_struct _struct.c
binascii binascii.c</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h3 class="wp-block-heading">4. 执行 configure 配置</h3>



<pre class="wp-block-code"><code>./configure LDFLAGS="-static" --disable-shared</code></pre>



<p>检查环境中是否还缺少编译依赖。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h3 class="wp-block-heading">5. 检查 Modules/Setup.local 文件</h3>



<p>再次检查 <code>Modules/Setup.local</code> 文件，确保执行 <code>configure</code> 后没有被覆盖或者置空：</p>



<ul>
<li>如果被修改覆盖了，需要重新写入 <code>Modules/Setup.local</code>，再执行第四步 <code>./configure LDFLAGS="-static" --disable-shared</code>。</li>



<li>如果还是被覆盖了，检查 <code>configure</code> 过程中的报错。</li>



<li>还是不行的，删除当前源码，重新解压出原始源码，再次尝试。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h3 class="wp-block-heading">6. 执行编译</h3>



<p>根据实际情况进行多线程编译（<code>-j</code> 后面接线程数）：</p>



<pre class="wp-block-code"><code>make -j10 LDFLAGS="-static" LINKFORSHARED=" "</code></pre>



<ul>
<li><code>LDFLAGS="-static"</code> 代表是将静态编译的参数传进编译器</li>



<li><code>LINKFORSHARED=" "</code> 是置空 <code>LINKFORSHARED</code> 变量，避免编译出共享库 <code>so</code></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h3 class="wp-block-heading">7. 测试运行</h3>



<p>当前目录直接测试运行是否正常，是否报缺失模块：</p>



<pre class="wp-block-code"><code>ldd ./python  # 查看执行文件是否静态
./python xxxx.py</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h3 class="wp-block-heading">8. 打包 Python3 程序</h3>



<p>程序运行正常就可以打包 python3 程序了（<code>bin</code> 文件 + <code>lib</code> <code>PY</code> 类型的依赖库）：</p>



<pre class="wp-block-code"><code>pwd
/root/0616/Python-3.9.23</code></pre>



<p>将程序临时安装在目录下的 <code>1</code> 路径：</p>



<pre class="wp-block-code"><code>make install LDFLAGS="-static" LINKFORSHARED=" " DESTDIR=/root/0616/Python-3.9.23/1</code></pre>



<p>将 <code>/root/0616/Python-3.9.23/2</code> 目录下的文件打包到目标环境上的机器即可运行：</p>



<pre class="wp-block-code"><code>ls /root/0616/Python-3.9.23/2/usr/local/lib/
libpython3.9.a  pkgconfig       python3.9</code></pre>



<p>执行以下命令复制文件到目标环境：</p>



<pre class="wp-block-code"><code>rsync -avP /root/0616/Python-3.9.23/2/usr/local/ root@new:/usr/local/
ln -sv /usr/local/bin/python3 /usr/bin/python3-static</code></pre>



<p>更简单的：只用复制静态 <code>python</code> 文件和 <code>usr/local/lib/python3.9</code> 到目标环境中即可。</p>



<p>官方文档（Building Python Statically）： https://wiki.python.org/moin/BuildStatically</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>静态编译 Python3 程序指南</title>
		<link>https://www.bhzhu203.com/2025/06/17/%e9%9d%99%e6%80%81%e7%bc%96%e8%af%91-python3-%e7%a8%8b%e5%ba%8f%e6%8c%87%e5%8d%97/</link>
		
		<dc:creator><![CDATA[bhzhu203]]></dc:creator>
		<pubDate>Tue, 17 Jun 2025 09:21:18 +0000</pubDate>
				<category><![CDATA[linux知识]]></category>
		<category><![CDATA[modules]]></category>
		<category><![CDATA[setup]]></category>
		<category><![CDATA[编译]]></category>
		<guid isPermaLink="false">https://www.bhzhu203.com/?p=483</guid>

					<description><![CDATA[1. 模块选择与确认 首先确定要静态编译进Python的模块，例如需要将asyn [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h1 class="wp-block-heading"></h1>



<h2 class="wp-block-heading">1. 模块选择与确认</h2>



<p>首先确定要静态编译进Python的模块，例如需要将asyncio模块静态编译到python3。可以通过查看<code>Modules/Setup</code>文件来了解详细的官方库编译项。</p>



<h2 class="wp-block-heading">2. 清理源码目录</h2>



<p>执行以下命令将源码目录恢复到初始状态：</p>



<pre class="wp-block-code"><code>make distclean</code></pre>



<h2 class="wp-block-heading">3. 配置 <code>Modules/Setup.local</code></h2>



<p>将需要静态编译的模块信息写入<code>Modules/Setup.local</code>文件，例如：</p>



<pre class="wp-block-code"><code>*static*
_asyncio _asynciomodule.c
_socket socketmodule.c
math mathmodule.c _math.c -DPy_BUILD_CORE_MODULE
select selectmodule.c
array arraymodule.c
_posixsubprocess _posixsubprocess.c
_contextvars _contextvarsmodule.c
_struct _struct.c
binascii binascii.c</code></pre>



<h2 class="wp-block-heading">4. 执行 <code>configure</code></h2>



<p>运行以下命令进行配置，确保环境中没有缺少编译依赖：</p>



<pre class="wp-block-code"><code>./configure LDFLAGS="-static" --disable-shared</code></pre>



<p>如果<code>Modules/Setup.local</code>被修改或覆盖，请重新写入该文件并再次执行此步骤。若仍存在问题，可检查configure过程中的报错信息。</p>



<h2 class="wp-block-heading">5. 编译 Python3 程序</h2>



<p>根据实际情况进行多线程编译：</p>



<pre class="wp-block-code"><code>make -j10 LDFLAGS="-static" LINKFORSHARED=" "</code></pre>



<h2 class="wp-block-heading">6. 测试运行与静态链接验证</h2>



<p>在当前目录直接测试运行程序，确保没有缺失模块：</p>



<pre class="wp-block-code"><code>ldd ./python   # 查看执行文件是否为静态编译
./python xxxx.py</code></pre>



<h2 class="wp-block-heading">7. 打包 Python3 程序</h2>



<p>将编译好的Python3程序打包到目标环境中：</p>



<pre class="wp-block-code"><code>pwd
/root/0616/Python-3.9.23

make install LDFLAGS="-static" LINKFORSHARED=" " DESTDIR=/root/0616/Python-3.9.23/1</code></pre>



<h2 class="wp-block-heading">8. 部署与复制</h2>



<p>将打包好的文件部署到目标环境：</p>



<pre class="wp-block-code"><code>ls /root/0616/Python-3.9.23/2/usr/local/lib/
libpython3.9.a  pkgconfig       python3.9

rsync -avP /root/0616/Python-3.9.23/2/usr/local/ root@new:/usr/local/
ln -sv /usr/local/bin/python3-static /usr/bin/python3</code></pre>



<h2 class="wp-block-heading">简化部署方案</h2>



<p>更简单的做法是只复制静态编译后的Python文件和相关依赖库到目标环境：</p>



<pre class="wp-block-code"><code>cp ./python3.9.static /target/path/
cp /root/0616/Python-3.9.23/2/usr/local/lib/python3.9 /target/path/</code></pre>



<p>这样，程序就可以在几乎任何发行版上零依赖运行。</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to make a btrfs snapshot writable?</title>
		<link>https://www.bhzhu203.com/2018/06/30/how-to-make-a-btrfs-snapshot-writable/</link>
		
		<dc:creator><![CDATA[bhzhu203]]></dc:creator>
		<pubDate>Sat, 30 Jun 2018 02:34:29 +0000</pubDate>
				<category><![CDATA[linux知识]]></category>
		<category><![CDATA[btrfs]]></category>
		<category><![CDATA[set]]></category>
		<category><![CDATA[snapshot]]></category>
		<guid isPermaLink="false">http://www.bhzhu203.com/?p=455</guid>

					<description><![CDATA[32 down vote accepted The btrfs manpage  [&#8230;]]]></description>
										<content:encoded><![CDATA[<div class="votecell post-layout--left">
<div class="vote"><span class="vote-count-post ">32</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> <span class="vote-accepted-on load-accepted-answer-date" title="loading when this answer was accepted...">accepted</span></div>
</div>
<div class="answercell post-layout--right">
<div class="post-text">
<p>The btrfs manpage fails to document the <code>property</code> subcommand, which I found by grep&#8217;ing the source. It&#8217;s also in <code>btrfs --help</code>.</p>
<p>To set a snapshot to read-write, you do something like this:</p>
<pre><code>btrfs property set -ts /path/to/snapshot ro false
</code></pre>
<p>Change that to <code>true</code> to set it to read-only.</p>
<p>You can also use <code>list</code> to see the available properties:</p>
<pre><code>btrfs property list -ts /path/to/snapshot
ro                  Set/get read-only flag of subvolume.
</code></pre>
<p><code>-t</code> specifies the type of object to work on, <code>s</code> means subvolume. Other options are <code>f</code> (filesystem), <code>i</code> (inode), and <code>d</code> (device). If you don&#8217;t specify, it&#8217;ll show all applicable ones (for list) or try to guess for get/set.</p>
<p>Edit: in the newest btrfs tools, there is a <code>btrfs-property</code> manpage documenting that subcommand, although it&#8217;s not mentioned in the main manpage at all. It&#8217;s also available as the <a href="https://btrfs.wiki.kernel.org/index.php/Manpage/btrfs-property" rel="noreferrer">btrfs-property page on the wiki</a>.</p>
<p>(Note: This requires a new-enough btrfs-tools. Apparently on Debian Wheezy, you&#8217;ll have to install the updated one from wheezy-backports; thanks <a href="https://unix.stackexchange.com/users/23542/artfulrobot">artfulrobot</a>).</p>
</div>
</div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>BTRFS Fun</title>
		<link>https://www.bhzhu203.com/2018/06/30/btrfs-fun/</link>
		
		<dc:creator><![CDATA[bhzhu203]]></dc:creator>
		<pubDate>Sat, 30 Jun 2018 02:31:56 +0000</pubDate>
				<category><![CDATA[linux知识]]></category>
		<category><![CDATA[btrfs]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[funtoo]]></category>
		<guid isPermaLink="false">http://www.bhzhu203.com/?p=453</guid>

					<description><![CDATA[https://www.funtoo.org/BTRFS_Fun#Using_s [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>https://www.funtoo.org/BTRFS_Fun#Using_snapshots_for_system_recovery_.28aka_Back_to_the_Future.29</p>
<div class="bs-announce bs-announce-main">
<p><a title="Support Funtoo" href="https://www.funtoo.org/Support_Funtoo">Support Funtoo</a> and help us grow! <b>Donate $15 per month and get a free SSD-based <a class="mw-redirect" title="Funtoo Hosting" href="https://www.funtoo.org/Funtoo_Hosting">Funtoo Virtual Container</a>.</b></p>
</div>
<div class="bs-callout bs-callout-warning">
<div class="bs-head">Important</div>
<p>BTRFS is still <b>experimental</b> even with latest Linux kernels (3.4-rc at date of writing) so be prepared to lose some data sooner or later or hit a severe issue/regressions/&#8221;itchy&#8221; bugs. Subliminal message: <b>Do not put critical data on BTRFS partitions</b>.</p>
</div>
<h1><span id="Introduction" class="mw-headline">Introduction</span></h1>
<p>BTRFS is an advanced filesystem mostly contributed by Sun/Oracle whose origins take place in 2007. A good summary is given in <a class="external autonumber" href="http://lwn.net/Articles/342892/">[1]</a>. BTRFS aims to provide a modern answer for making storage more flexible and efficient. According to its main contributor, Chris Mason, the goal was &#8220;to let Linux scale for the storage that will be available. Scaling is not just about addressing the storage but also means being able to administer and to manage it with a clean interface that lets people see what&#8217;s being used and makes it more reliable.&#8221; (Ref. <a class="external free" href="http://en.wikipedia.org/wiki/Btrfs">http://en.wikipedia.org/wiki/Btrfs</a>).</p>
<p>Btrfs, often compared to ZFS, is offering some interesting features like:</p>
<ul>
<li>Using very few fixed location metadata, thus allowing an existing ext2/ext3 filesystem to be &#8220;upgraded&#8221; in-place to BTRFS.</li>
<li>Operations are transactional</li>
<li>Online volume defragmentation (online filesystem check is on the radar but is not yet implemented).</li>
<li>Built-in storage pool capabilities (no need for LVM)</li>
<li>Built-in RAID capabilities (both for the data and filesystem metadata). RAID-5/6 is planned for 3.5 kernels</li>
<li>Capabilities to grow/shrink the volume</li>
<li>Subvolumes and snapshots (extremely powerful, you can &#8220;rollback&#8221; to a previous filesystem state as if nothing had happened).</li>
<li>Copy-On-Write</li>
<li>Usage of B-Trees to store the internal filesystem structures (B-Trees are known to have a logarithmic growth in depth, thus making them more efficient when scanning)</li>
</ul>
<h1><span id="Requirements" class="mw-headline">Requirements</span></h1>
<p>A recent Linux kernel (BTRFS metadata format evolves from time to time and mounting using a recent Linux kernel can make the BTRFS volume unreadable with an older kernel revision, e.g. Linux 2.6.31 vs Linux 2.6.30). You must also use sys-fs/btrfs-progs (0.19 or better use -9999 which points to the git repository).</p>
<h1><span id="Playing_with_BTRFS_storage_pool_capabilities" class="mw-headline">Playing with BTRFS storage pool capabilities</span></h1>
<p>Whereas it would possible to use btrfs just as you are used to under a non-LVM system, it shines in using its built-in storage pool capabilities. Tired of playing with LVM ? <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Good news: you do not need it anymore with btrfs.</p>
<h2><span id="Setting_up_a_storage_pool" class="mw-headline">Setting up a storage pool</span></h2>
<p>BTRFS terminology is a bit confusing. If you already have used another &#8216;advanced&#8217; filesystem like ZFS or some mechanism like LVM, it&#8217;s good to know that there are many correlations. In the BTRFS world, the word <i>volume</i> corresponds to a storage <i>pool</i> (ZFS) or a <i>volume group</i> (LVM). Ref. <a class="external free" href="http://www.rkeene.org/projects/info/wiki.cgi/165">http://www.rkeene.org/projects/info/wiki.cgi/165</a></p>
<p>The test bench uses disk images through loopback devices. Of course, in a real world case, you will use local drives or units though a SAN. To start with, 5 devices of 1 GiB are allocated:</p>
<pre class="code">#<span class="code_input"> dd if=/dev/zero of=/tmp/btrfs-vol0.img bs=1G count=1</span>
#<span class="code_input"> dd if=/dev/zero of=/tmp/btrfs-vol1.img bs=1G count=1</span>
#<span class="code_input"> dd if=/dev/zero of=/tmp/btrfs-vol2.img bs=1G count=1</span>
#<span class="code_input"> dd if=/dev/zero of=/tmp/btrfs-vol3.img bs=1G count=1</span>
#<span class="code_input"> dd if=/dev/zero of=/tmp/btrfs-vol4.img bs=1G count=1</span>
</pre>
<p>Then attached:</p>
<pre class="code">#<span class="code_input"> losetup /dev/loop0 /tmp/btrfs-vol0.img</span>
#<span class="code_input"> losetup /dev/loop1 /tmp/btrfs-vol1.img</span>
#<span class="code_input"> losetup /dev/loop2 /tmp/btrfs-vol2.img</span>
#<span class="code_input"> losetup /dev/loop3 /tmp/btrfs-vol3.img</span>
#<span class="code_input"> losetup /dev/loop4 /tmp/btrfs-vol4.img</span>
</pre>
<h2><span id="Creating_the_initial_volume_.28pool.29" class="mw-headline">Creating the initial volume (pool)</span></h2>
<p>BTRFS uses different strategies to store data and for the filesystem metadata (ref. <a class="external free" href="https://btrfs.wiki.kernel.org/index.php/Using_Btrfs_with_Multiple_Devices">https://btrfs.wiki.kernel.org/index.php/Using_Btrfs_with_Multiple_Devices</a>).</p>
<p>By default the behavior is:</p>
<ul>
<li>metadata is <b>replicated</b> on all of the devices. If a single device is used the metadata is duplicated inside this single device (useful in case of corruption or bad sector, there is a higher chance that one of the two copies is clean). To tell btrfs to maintain a single copy of the metadata, just use <i>single</i>. Remember: <b>dead metadata = dead volume with no chance of recovery.</b></li>
<li>data is <b>spread</b> amongst all of the devices (this means no redundancy; any data block left on a defective device will be inaccessible)</li>
</ul>
<p>To create a BTRFS volume made of multiple devices with default options, use:</p>
<pre class="code">#<span class="code_input"> mkfs.btrfs /dev/loop0 /dev/loop1 /dev/loop2 </span>
</pre>
<p>To create a BTRFS volume made of a single device with a single copy of the metadata (dangerous!), use:</p>
<pre class="code">#<span class="code_input"> mkfs.btrfs -m single /dev/loop0</span>
</pre>
<p>To create a BTRFS volume made of multiple devices with metadata spread amongst all of the devices, use:</p>
<pre class="code">#<span class="code_input"> mkfs.btrfs -m raid0 /dev/loop0 /dev/loop1 /dev/loop2 </span>
</pre>
<p>To create a BTRFS volume made of multiple devices, with metadata spread amongst all of the devices and data mirrored on all of the devices (you probably don&#8217;t want this in a real setup), use:</p>
<pre class="code">#<span class="code_input"> mkfs.btrfs -m raid0 -d raid1 /dev/loop0 /dev/loop1 /dev/loop2 </span>
</pre>
<p>To create a fully redundant BTRFS volume (data and metadata mirrored amongst all of the devices), use:</p>
<pre class="code">#<span class="code_input"> mkfs.btrfs -d raid1 /dev/loop0 /dev/loop1 /dev/loop2 </span>
</pre>
<div class="bs-callout bs-callout-info">
<div class="bs-head">Note</div>
<p>Technically you can use anything as a physical volume: you can have a volume composed of 2 local hard drives, 3 USB keys, 1 loopback device pointing to a file on a NFS share and 3 logical devices accessed through your SAN (you would be an idiot, but you can, nevertheless). Having different physical volume sizes would lead to issues, but it works :-).</p>
</div>
<h2><span id="Checking_the_initial_volume" class="mw-headline">Checking the initial volume</span></h2>
<p>To verify the devices of which BTRFS volume is composed, just use <b>btrfs-show <i>device</i> </b> (old style) or <b>btrfs filesystem show <i>device</i> </b> (new style). You need to specify one of the devices (the metadata has been designed to keep a track of the what device is linked what other device). If the initial volume was set up like this:</p>
<pre class="code">#<span class="code_input"> mkfs.btrfs /dev/loop0 /dev/loop1 /dev/loop2</span>

WARNING! - Btrfs Btrfs v0.19 IS EXPERIMENTAL
WARNING! - see http://btrfs.wiki.kernel.org before using

adding device /dev/loop1 id 2
adding device /dev/loop2 id 3
fs created label (null) on /dev/loop0
        nodesize 4096 leafsize 4096 sectorsize 4096 size 3.00GB
Btrfs Btrfs v0.19
</pre>
<p>It can be checked with one of these commands (They are equivalent):</p>
<pre class="code">#<span class="code_input"> btrfs filesystem show /dev/loop0</span>
#<span class="code_input"> btrfs filesystem show /dev/loop1</span>
#<span class="code_input"> btrfs filesystem show /dev/loop2</span>
</pre>
<p>The result is the same for all commands:</p>
<pre>Label: none  uuid: 0a774d9c-b250-420e-9484-b8f982818c09
        Total devices 3 FS bytes used 28.00KB
        devid    3 size 1.00GB used 263.94MB path /dev/loop2
        devid    1 size 1.00GB used 275.94MB path /dev/loop0
        devid    2 size 1.00GB used 110.38MB path /dev/loop1
</pre>
<p>To show all of the volumes that are present:</p>
<pre class="code">#<span class="code_input"> btrfs filesystem show</span>
Label: none  uuid: 0a774d9c-b250-420e-9484-b8f982818c09
        Total devices 3 FS bytes used 28.00KB
        devid    3 size 1.00GB used 263.94MB path /dev/loop2
        devid    1 size 1.00GB used 275.94MB path /dev/loop0
        devid    2 size 1.00GB used 110.38MB path /dev/loop1

Label: none  uuid: 1701af39-8ea3-4463-8a77-ec75c59e716a
        Total devices 1 FS bytes used 944.40GB
        devid    1 size 1.42TB used 1.04TB path /dev/sda2

Label: none  uuid: 01178c43-7392-425e-8acf-3ed16ab48813
        Total devices 1 FS bytes used 180.14GB
        devid    1 size 406.02GB used 338.54GB path /dev/sda4
</pre>
<div class="bs-callout bs-callout-danger">
<div class="bs-head">Warning</div>
<p>BTRFS wiki mentions that <b>btrfs device scan</b> should be performed, consequence of not doing the incantation? Volume not seen?</p>
</div>
<h2><span id="Mounting_the_initial_volume" class="mw-headline">Mounting the initial volume</span></h2>
<p>BTRFS volumes can be mounted like any other filesystem. The cool stuff at the top on the sundae is that the design of the BTRFS metadata makes it possible to use any of the volume devices. The following commands are equivalent:</p>
<pre class="code">#<span class="code_input"> mount /dev/loop0 /mnt</span>
#<span class="code_input"> mount /dev/loop1 /mnt</span>
#<span class="code_input"> mount /dev/loop2 /mnt</span>
</pre>
<p>For every physical device used for mounting the BTRFS volume <tt>df -h</tt> reports the same (in all cases 3 GiB of &#8220;free&#8221; space is reported):</p>
<pre class="code">#<span class="code_input"> df -h</span>
Filesystem      Size  Used Avail Use% Mounted on
/dev/loop1      3.0G   56K  1.8G   1% /mnt
</pre>
<p>The following command prints very useful information (like how the BTRFS volume has been created):</p>
<pre class="code">#<span class="code_input"> btrfs filesystem df /mnt      </span>
Data, RAID0: total=409.50MB, used=0.00
Data: total=8.00MB, used=0.00
System, RAID1: total=8.00MB, used=4.00KB
System: total=4.00MB, used=0.00
Metadata, RAID1: total=204.75MB, used=28.00KB
Metadata: total=8.00MB, used=0.00
</pre>
<p>By the way, as you can see, for the btrfs command the mount point should be specified, not one of the physical devices.</p>
<h2><span id="Shrinking_the_volume" class="mw-headline">Shrinking the volume</span></h2>
<p>A common practice in system administration is to leave some head space, instead of using the whole capacity of a storage pool (just in case). With btrfs one can easily shrink volumes. Let&#8217;s shrink the volume a bit (about 25%):</p>
<pre class="code">#<span class="code_input"> btrfs filesystem resize -500m /mnt</span>
#<span class="code_input"> dh -h</span>
/dev/loop1      2.6G   56K  1.8G   1% /mnt
</pre>
<p>And yes, it is an on-line resize, there is no need to umount/shrink/mount. So no downtimes! <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> However, a BTRFS volume requires a minimal size&#8230; if the shrink is too aggressive the volume won&#8217;t be resized:</p>
<pre class="code">#<span class="code_input"> btrfs filesystem resize -1g /mnt  </span>
Resize '/mnt' of '-1g'
ERROR: unable to resize '/mnt'
</pre>
<h2><span id="Growing_the_volume" class="mw-headline">Growing the volume</span></h2>
<p>This is the opposite operation, you can make a BTRFS grow to reach a particular size (e.g. 150 more megabytes):</p>
<pre class="code">#<span class="code_input"> btrfs filesystem resize +150m /mnt</span>
Resize '/mnt' of '+150m'
#<span class="code_input"> dh -h</span>
/dev/loop1      2.7G   56K  1.8G   1% /mnt
</pre>
<p>You can also take an <i>&#8220;all you can eat&#8221;</i> approach via the <b>max</b> option, meaning all of the possible space will be used for the volume:</p>
<pre class="code">#<span class="code_input"> btrfs filesystem resize max /mnt</span>
Resize '/mnt' of 'max'
#<span class="code_input"> dh -h</span>
/dev/loop1      3.0G   56K  1.8G   1% /mnt
</pre>
<h2><span id="Adding_a_new_device_to_the_BTRFS_volume" class="mw-headline">Adding a new device to the BTRFS volume</span></h2>
<p>To add a new device to the volume:</p>
<pre class="code">#<span class="code_input"> btrfs device add /dev/loop4 /mnt </span>
oxygen ~ # btrfs filesystem show /dev/loop4 
Label: none  uuid: 0a774d9c-b250-420e-9484-b8f982818c09
        Total devices 4 FS bytes used 28.00KB
        devid    3 size 1.00GB used 263.94MB path /dev/loop2
        devid    4 size 1.00GB used 0.00 path /dev/loop4
        devid    1 size 1.00GB used 275.94MB path /dev/loop0
        devid    2 size 1.00GB used 110.38MB path /dev/loop1 
</pre>
<p>Again, no need to umount the volume first as adding a device is an on-line operation (the device has no space used yet hence the &#8216;0.00&#8217;). The operation is not finished as we must tell btrfs to prepare the new device (i.e. rebalance/mirror the metadata and the data between all devices):</p>
<pre class="code">#<span class="code_input"> btrfs filesystem balance /mnt</span>
#<span class="code_input"> btrfs filesystem show /dev/loop4</span>
Label: none  uuid: 0a774d9c-b250-420e-9484-b8f982818c09
        Total devices 4 FS bytes used 28.00KB
        devid    3 size 1.00GB used 110.38MB path /dev/loop2
        devid    4 size 1.00GB used 366.38MB path /dev/loop4
        devid    1 size 1.00GB used 378.38MB path /dev/loop0
        devid    2 size 1.00GB used 110.38MB path /dev/loop1
</pre>
<div class="bs-callout bs-callout-info">
<div class="bs-head">Note</div>
<p>Depending on the sizes and what is in the volume a balancing operation could take several minutes or hours.</p>
</div>
<h2><span id="Removing_a_device_from_the_BTRFS_volume" class="mw-headline">Removing a device from the BTRFS volume</span></h2>
<pre class="code">#<span class="code_input"> btrfs device delete /dev/loop2 /mnt</span>
#<span class="code_input"> btrfs filesystem show /dev/loop0   </span>
Label: none  uuid: 0a774d9c-b250-420e-9484-b8f982818c09
        Total devices 4 FS bytes used 28.00KB
        devid    4 size 1.00GB used 264.00MB path /dev/loop4
        devid    1 size 1.00GB used 268.00MB path /dev/loop0
        devid    2 size 1.00GB used 0.00 path /dev/loop1
        *** Some devices missing
#<span class="code_input"> df -h</span>
Filesystem      Size  Used Avail Use% Mounted on
/dev/loop1      3.0G   56K  1.5G   1% /mnt
</pre>
<p>Here again, removing a device is totally dynamic and can be done as an on-line operation! Note that when a device is removed, its content is transparently redistributed among the other devices.</p>
<p>Obvious points:</p>
<ul>
<li><b>** DO NOT UNPLUG THE DEVICE BEFORE THE END OF THE OPERATION, DATA LOSS WILL RESULT**</b></li>
<li>If you have used raid0 in either metadata or data at the BTRFS volume creation you will end in a unusable volume if one of the the devices fails before being properly removed from the volume as some stripes will be lost.</li>
</ul>
<p>Once you add a new device to the BTRFS volume as a replacement for a removed one, you can cleanup the references to the missing device:</p>
<pre class="code">#<span class="code_input"> btrfs device delete missing</span>
</pre>
<h2><span id="Using_a_BTRFS_volume_in_degraded_mode" class="mw-headline">Using a BTRFS volume in degraded mode</span></h2>
<div class="bs-callout bs-callout-danger">
<div class="bs-head">Warning</div>
<p>It is not possible to use a volume in degraded mode if raid0 has been used for data/metadata and the device had not been properly removed with <b>btrfs device delete</b> (some stripes will be missing). The situation is even worse if RAID0 is used for the the metadata: trying to mount a BTRFS volume in read/write mode while not all the devices are accessible <b>will simply kill the remaining metadata, hence making the BTRFS volume totally unusable</b>&#8230; you have been warned! <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</div>
<p>If you use raid1 or raid10 for data AND metadata and you have a usable submirror accessible (consisting of 1 drive in case of RAID1 or the two drive of the same RAID0 array in case of RAID10), you can mount the array in degraded mode in the case of some devices are missing (e.g. dead SAN link or dead drive) :</p>
<pre class="code">#<span class="code_input"> mount -o degraded /dev/loop0 /mnt</span>
</pre>
<p>If you use RAID0 (and have one of your drives inaccessible) the metadata or RAID10 but not enough drives are on-line to even get a degraded mode possible, btrfs will refuse to mount the volume:</p>
<pre class="code">#<span class="code_input"> mount /dev/loop0 /mnt</span>
mount: wrong fs type, bad option, bad superblock on /dev/loop0,
       missing codepage or helper program, or other error
       In some cases useful info is found in syslog - try
       dmesg | tail  or so
</pre>
<p>The situation is no better if you have used RAID1 for the metadata and RAID0 for the data, you can mount the drive in degraded mode but you will encounter problems while accessing your files:</p>
<pre class="code">#<span class="code_input"> cp /mnt/test.dat /tmp </span>
cp: reading `/mnt/test.dat': Input/output error
cp: failed to extend `/tmp/test.dat': Input/output error
</pre>
<h1><span id="Playing_with_subvolumes_and_snapshots" class="mw-headline">Playing with subvolumes and snapshots</span></h1>
<h2><span id="A_story_of_boxes...." class="mw-headline">A story of boxes&#8230;.</span></h2>
<p>When you think about subvolumes in BTRFS, think about boxes. Each one of those can contain items and other smaller boxes (&#8220;sub-boxes&#8221;) which in turn can also contains items and boxes (sub-sub-boxes) and so on. Each box and items has a number and a name, except for the top level box, which has only a number (zero). Now imagine that all of the boxes are semi-opaque: you can see what they contain if you are outside the box but you can&#8217;t see outside when you are inside the box. Thus, depending on the box you are in you can view either all of the items and sub-boxes (top level box) or only a part of them (any other box but the top level one). To give you a better idea of this somewhat abstract explanation let&#8217;s illustrate a bit:</p>
<pre>(0) --+-&gt; Item A (1)
      |
      +-&gt; Item B (2)
      |
      +-&gt; Sub-box 1 (3) --+-&gt; Item C (4)
      |                   |
      |                   +-&gt; Sub-sub-box 1.1 (5) --+-&gt; Item D (6)
      |                   |                         | 
      |                   |                         +-&gt; Item E (7)
      |                   |                         |
      |                   |                         +-&gt; Sub-Sub-sub-box 1.1.1 (8) ---&gt; Item F (9)
      |                   +-&gt; Item F (10)
      |
      +-&gt; Sub-box 2 (11) --&gt; Item G (12)                    
</pre>
<p>What you see in the hierarchy depends on where you are (note that the top level box numbered 0 doesn&#8217;t have a name, you will see why later). So:</p>
<ul>
<li>If you are in the node named top box (numbered 0) you see everything, i.e. things numbered 1 to 12</li>
<li>If you are in &#8220;Sub-sub-box 1.1&#8221; (numbered 5), you see only things 6 to 9</li>
<li>If you are in &#8220;Sub-box 2&#8221; (numbered 11), you only see what is numbered 12</li>
</ul>
<p>Did you notice? We have two items named &#8216;F&#8217; (respectively numbered 9 and 10). This is not a typographic error, this is just to illustrate the fact that every item lives its own peaceful existence in its own box. Although they have the same name, 9 and 10 are two distinct and unrelated objects (of course it is impossible to have two objects named &#8216;F&#8217; in the same box, even they would be numbered differently).</p>
<h2><span id="..._applied_to_BTRFS.21_.28or.2C_.22What_is_a_volume.2Fsubvolume.3F.22.29" class="mw-headline">&#8230; applied to BTRFS! (or, &#8220;What is a volume/subvolume?&#8221;)</span></h2>
<p>BTRFS subvolumes work in the exact same manner, with some nuances:</p>
<ul>
<li>First, imagine a frame that surrounds the whole hierarchy (represented in dots below). This is your BTRFS <b>volume</b>. A bit abstract at first glance, but BTRFS volumes have no tangible existence, they are just an <i>aggregation</i> of devices tagged as being clustered together (that fellowship is created when you invoke <b>mkfs.btrfs</b> or <b>btrfs device add</b>).</li>
<li>Second, the first level of hierarchy contains <b>only</b> a single box numbered zero which can never be destroyed (because everything it contains would also be destroyed).</li>
</ul>
<p>If in our analogy of a nested boxes structure we used the word <b>&#8220;box&#8221;</b>, in the real BTRFS word we use the word <b>&#8220;subvolume&#8221;</b> (box =&gt; subvolume). Like in our boxes analogy, all subvolumes hold a unique number greater than zero and a name, with the exception of root subvolume located at the very first level of the hierarchy which is <i>always</i> numbered zero and has no name (BTRFS tools destroy subvolumes by their name not their number so <b>no name = no possible destruction</b>. This is a totally intentional architectural choice, not a flaw).</p>
<p>Here is a typical hierarchy:</p>
<pre>.....BTRFS Volume................................................................................................................................
.
.  Root subvolume (0) --+-&gt; Subvolume SV1 (258) ---&gt; Directory D1 --+-&gt; File F1
.                       |                                           |
.                       |                                           +-&gt; File F2
.                       |
.                       +-&gt; Directory D1 --+-&gt; File F1
.                       |                  |
.                       |                  +-&gt; File F2
.                       |                  |
.                       |                  +-&gt; File F3
.                       |                  |
.                       |                  +-&gt; Directory D11 ---&gt; File F4
.                       +-&gt; File F1
.                       |
.                       +-&gt; Subvolume SV2 (259) --+-&gt; Subvolume SV21 (260)
.                                                 |
.                                                 +-&gt; Subvolume SV22 (261) --+-&gt; Directory D2 ---&gt; File F4
.                                                                            |
.                                                                            +-&gt; Directory D3 --+-&gt; Subvolume SV221 (262) ---&gt; File F5
.                                                                            |                  |
.                                                                            |                  +-&gt; File F6
.                                                                            |                  |
.                                                                            |                  +-&gt; File F7
.                                                                            |
.                                                                            +-&gt; File F8
.
.....................................................................................................................................
</pre>
<p>Maybe you have a question: &#8220;Okay, What is the difference between a directory and a subvolume? Both can can contain something!&#8221;. To further confuse you, here is what users get if they reproduce the first level hierarchy on a real machine:</p>
<pre class="code">#<span class="code_input"> ls -l</span>
total 0
drwx------ 1 root root 0 May 23 12:48 SV1
drwxr-xr-x 1 root root 0 May 23 12:48 D1
-rw-r--r-- 1 root root 0 May 23 12:48 F1
drwx------ 1 root root 0 May 23 12:48 SV2
</pre>
<p>Although subvolumes SV1 and SV2 have been created with special BTRFS commands they appear just as if they were ordinary directories! A subtle nuance exists, however: think again at our boxes analogy we did before and map the following concepts in the following manner:</p>
<ul>
<li>a subvolume : the semi-opaque <b>box</b></li>
<li>a directory : a <i>sort of</i> <b>item</b> (that can contain something even another subvolume)</li>
<li>a file : <i>another sort of</i> <b>item</b></li>
</ul>
<p>So, in the internal filesystem metadata SV1 and SV2 are stored in a different manner than D1 (although this is transparently handled for users). You can, however see SV1 and SV2 for what they are (subvolumes) by running the following command (subvolume numbered (0) has been mounted on /mnt):</p>
<pre class="code">#<span class="code_input"> btrfs subvolume list /mnt</span>
ID 258 top level 5 path SV1
ID 259 top level 5 path SV2
</pre>
<p>What would we get if we create SV21 and SV22 inside of SV2? Let&#8217;s try! Before going further you should be aware that a subvolume is created by invoking the magic command <b>btrfs subvolume create</b>:</p>
<pre class="code">#<span class="code_input"> cd /mnt/SV2</span>
#<span class="code_input"> btrfs subvolume create SV21</span>
Create subvolume './SV21'
#<span class="code_input"> btrfs subvolume create SV22</span>
Create subvolume './SV22'
#<span class="code_input"> btrfs subvolume list /mnt  </span>
ID 258 top level 5 path SV1
ID 259 top level 5 path SV2
ID 260 top level 5 path SV2/SV21
ID 261 top level 5 path SV2/SV22
</pre>
<p>Again, invoking <b>ls</b> in /mnt/SV2 will report the subvolumes as being directories:</p>
<pre class="code">#<span class="code_input"> ls -l</span>
total 0
drwx------ 1 root root 0 May 23 13:15 SV21
drwx------ 1 root root 0 May 23 13:15 SV22
</pre>
<h2><span id="Changing_the_point_of_view_on_the_subvolumes_hierarchy" class="mw-headline">Changing the point of view on the subvolumes hierarchy</span></h2>
<p>At some point in our boxes analogy we have talked about what we see and what we don&#8217;t see depending on our location in the hierarchy. Here lies a big important point: whereas most of the BTRFS users mount the root subvolume (subvolume id = 0, we will retain the <i>root subvolume</i> terminology) in their VFS hierarchy thus making visible the whole hierarchy contained in the BTRFS volume, it is absolutely possible to mount only a <i>subset</i> of it. How that could be possible? Simple: Just specify the subvolume number when you invoke mount. For example, to mount the hierarchy in the VFS starting at subvolume SV22 (261) do the following:</p>
<pre class="code">#<span class="code_input"> mount -o subvolid=261 /dev/loop0 /mnt</span>
</pre>
<p>Here lies an important notion not disclosed in the previous paragraph: although both directories and subvolumes can act as containers, <b>only subvolumes can be mounted in a VFS hierarchy</b>. It is a fundamental aspect to remember: you cannot mount a sub-part of a subvolume in the VFS; you can only mount the subvolume in itself. Considering the hierarchy schema in the previous section, if you want to access the directory D3 you have three possibilities:</p>
<ol>
<li>Mount the non-named subvolume (numbered 0) and access D3 through /mnt/SV2/SV22/D3 if the non-named subvolume is mounted in /mnt</li>
<li>Mount the subvolume SV2 (numbered 259) and access D3 through /mnt/SV22/D3 if the the subvolume SV2 is mounted in /mnt</li>
<li>Mount the subvolume SV22 (numbered 261) and access D3 through /mnt/D3 if the the subvolume SV22 is mounted in /mnt</li>
</ol>
<p>This is accomplished by the following commands, respectively:</p>
<pre class="code">#<span class="code_input"> mount -o subvolid=0 /dev/loop0 /mnt</span>
#<span class="code_input"> mount -o subvolid=259 /dev/loop0 /mnt</span>
#<span class="code_input"> mount -o subvolid=261 /dev/loop0 /mnt</span>
</pre>
<div class="bs-callout bs-callout-info">
<div class="bs-head">Note</div>
<p>When a subvolume is mounted in the VFS, everything located &#8220;above&#8221; the subvolume is hidden. Concretely, if you mount the subvolume numbered 261 in /mnt, you only see what is under SV22, you won&#8217;t see what is located above SV22 like SV21, SV2, D1, SV1, etc.</p>
</div>
<h2><span id="The_default_subvolume" class="mw-headline">The default subvolume</span></h2>
<p>$100 questions: 1. &#8220;If I don&#8217;t put &#8216;subvolid&#8217; in the command line, 1. how does the kernel know which one of the subvolumes it has to mount? 2. Does Omitting the &#8216;subvolid&#8217; means automatically &#8216;mount subvolume numbered 0&#8217;?&#8221;. Answers: 1. BTRFS magic! <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 2. No, not necessarily, you can choose something other than the non-named subvolume.</p>
<p>When you create a brand new BTRFS filesystem, the system not only creates the initial the root subvolume (numbered 0) but also tags it as being the <b>default subvolume</b>. When you ask the operating system to mount a subvolume contained in a BTRFS volume without specifying a subvolume number, it determines which of the existing subvolumes has been tagged as &#8220;default subvolume&#8221; and mounts it. If none of the exiting subvolumes has the tag &#8220;default subvolume&#8221; (e.g. because the default subvolume has been deleted), the mount command gives up with a rather cryptic message:</p>
<pre class="code">#<span class="code_input"> mount /dev/loop0 /mnt</span>
mount: No such file or directory
</pre>
<p>It is also possible to change at any time which subvolume contained in a BTRFS volume is considered the default volume. This is accomplished with <b>btrfs subvolume set-default</b>. The following tags the subvolume 261 as being the default:</p>
<pre class="code">#<span class="code_input"> btrfs subvolume set-default 261 /mnt</span>
</pre>
<p>After that operation, doing the following is exactly the same:</p>
<pre class="code">#<span class="code_input"> mount /dev/loop0 /mnt</span>
#<span class="code_input"> mount -o subvolid=261 /dev/loop0 /mnt</span>
</pre>
<div class="bs-callout bs-callout-info">
<div class="bs-head">Note</div>
<p>The chosen new default subvolume must be visible in the VFS when you invoke <i>btrfs subvolume set-default&#8217;</i></p>
</div>
<h2><span id="Deleting_subvolumes" class="mw-headline">Deleting subvolumes</span></h2>
<p>Question: &#8220;As subvolumes appear like directories, can I delete a subvolume by doing an rm -rf on it?&#8221;. Answer: Yes, you <i>can</i>, but that way is not the most elegant, especially when it contains several gigabytes of data scattered on thousands of files, directories and maybe other subvolumes located in the one you want to remove. It isn&#8217;t elegant because <i>rm -rf</i> could take several minutes (or even hours!) to complete whereas something else can do the same job in the fraction of a second.</p>
<p>&#8220;Huh?&#8221; Yes perfectly possible, and here is the cool goodie for the readers who arrived at this point: when you want to remove a subvolume, use <b>btrfs subvolume delete</b> instead of <b>rm -rf</b>. That btrfs command will remove the snapshots in a fraction of a second, even it contains several gigabytes of data!</p>
<div class="bs-callout bs-callout-danger">
<div class="bs-head">Warning</div>
<ul>
<li>You can <b>never</b> remove the root subvolume of a BTRFS volume as <b>btrfs delete</b> expects a subvolume name (again: this is not a flaw in the design of BTRFS; removing the subvolume numbered 0 would destroy the entirety of a BTRFS volume&#8230;too dangerous).</li>
<li>If the subvolume you delete was tagged as the default subvolume you will have to designate another default subvolume or explicitly tell the system which one of the subvolumes has to be mounted)</li>
</ul>
</div>
<p>An example: considering our initial example given <a title="BTRFS Fun" href="https://www.funtoo.org/BTRFS_Fun#..._applied_to_BTRFS.21_.28or_what_is_a_volume.2Fsubvolume.29">above</a> and supposing you have mounted non-named subvolume numbered 0 in /mnt, you can remove SV22 by doing:</p>
<pre class="code">#<span class="code_input"> btrfs subvolume delete /mnt/SV2/SV22</span>
</pre>
<p>Obviously the BTRFS volume will look like this after the operation:</p>
<pre>.....BTRFS Volume................................................................................................................................
.
.  (0) --+-&gt; Subvolume SV1 (258) ---&gt; Directory D1 --+-&gt; File F1
.        |                                           |
.        |                                           +-&gt; File F2
.        |
.        +-&gt; Directory D1 --+-&gt; File F1
.        |                  |
.        |                  +-&gt; File F2
.        |                  |
.        |                  +-&gt; File F3
.        |                  |
.        |                  +-&gt; Directory D11 ---&gt; File F4
.        +-&gt; File F1
.        |
.        +-&gt; Subvolume SV2 (259) --+-&gt; Subvolume SV21 (260)
.....................................................................................................................................
</pre>
<h2><span id="Snapshot_and_subvolumes" class="mw-headline">Snapshot and subvolumes</span></h2>
<p>If you have a good comprehension of what a subvolume is, understanding what a snapshot is won&#8217;t be a problem: a snapshot is a subvolume with some initial contents. &#8220;Some initial contents&#8221; here means an exact copy.</p>
<p>When you think about snapshots, think about copy-on-write: the data blocks are not duplicated between a mounted subvolume and its snapshot unless you start to make changes to the files (a snapshot can occupy nearly zero extra space on the disk). At time goes on, more and more data blocks will be changed, thus making snapshots &#8220;occupy&#8221; more and more space on the disk. It is therefore recommended to keep only a minimal set of them and remove unnecessary ones to avoid wasting space on the volume. The following illustrates how to take a snaphot of the VFS root:</p>
<pre class="code">#<span class="code_input"> btrfs subvolume snapshot / /snap-2011-05-23</span>
Create a snapshot of '/' in '//snap-2011-05-23'
</pre>
<p>Once created, the snapshot will persist in /snap-2011-05-23 as long as you don&#8217;t delete it. Note that the snapshot contents will remain exactly the same it was at the time is was taken (as long as you don&#8217;t make changes&#8230; BTRFS snapshots are writable!). A drawback of having snapshots: if you delete some files in the original filesystem, the snapshot still contains them and the disk blocks can&#8217;t be claimed as free space. Remember to remove unwanted snapshots and keep a bare minimal set of them.</p>
<h2><span id="Listing_and_deleting_snaphots" class="mw-headline">Listing and deleting snaphots</span></h2>
<p>As there is no distinction between a snapshot and a subvolume, snapshots are managed with the exact same commands, especially when the time has come to delete some of them. An interesting feature in BTRFS is that snapshots are writable. You can take a snapshot and make changes in the files/directories it contains. A word of caution: there are no undo capbilities! What has been changed has been changed forever&#8230; If you need to do several tests just take several snapshots or, better yet, snapshot your snapshot then do whatever you need in this copy-of-the-copy :-).</p>
<h2><span id="Using_snapshots_for_system_recovery_.28aka_Back_to_the_Future.29" class="mw-headline">Using snapshots for system recovery (aka Back to the Future)</span></h2>
<p>Here is where BTRFS can literally be a lifeboat. Suppose you want to apply some updates via <b>emerge -uaDN @world</b> but you want to be sure that you can jump back into the past in case something goes seriously wrong after the system update (does libpng14 remind you of anything?!). Here is the &#8220;putting-things-together part&#8221; of the article!</p>
<p>The following only applies if your VFS root and system directories containing <b>/sbin, /bin, /usr, /etc&#8230;.</b> are located on a BTRFS volume. To make things simple, the whole structure is supposed to be located in the SAME subvolume of the same BTRFS volume.</p>
<p>To jump back into the past you have at least two options:</p>
<ol>
<li>Fiddle with the default subvolume numbers</li>
<li>Use the kernel command line parameters in the bootloader configuration files</li>
</ol>
<p>In all cases you must take a snapshot of your VFS root *before* updating the system:</p>
<pre class="code">#<span class="code_input"> btrfs subvolume snapshot / /before-updating-2011-05-24</span>
Create a snapshot of '/' in '//before-updating-2011-05-24'
</pre>
<div class="bs-callout bs-callout-info">
<div class="bs-head">Note</div>
<p>Hint: You can create an empty file at the root of your snapshot with the name of your choice to help you easily identify which subvolume is the currently mounted one (e.g. if the snapshot has been named <b>before-updating-2011-05-24</b>, you can use a slightly different name like <b>current-is-before-updating-2011-05-24</b> =&gt; <b>touch /before-updating-2011-05-24/current-is-before-updating-2011-05-24</b>). This is extremly useful if you are dealing with several snapshots.</p>
</div>
<p>There is no &#8220;better&#8221; way; it&#8217;s just a question of personal preference.</p>
<h3><span id="Way_.231:_Fiddle_with_the_default_subvolume_number" class="mw-headline">Way #1: Fiddle with the default subvolume number</span></h3>
<p><b>Hypothesis: </b></p>
<ul>
<li>Your &#8220;production&#8221; VFS root partition resides in the root subvolume (subvolid=0),</li>
<li>Your /boot partition (where the bootloader configuration files are stored) is on another standalone partition</li>
</ul>
<p>First search for the newly created subvolume number:</p>
<pre class="code">#<span class="code_input"> btrfs subvolume list / </span>
'''ID 256''' top level 5 path before-updating-2011-05-24
</pre>
<p>&#8216;256&#8217; is the ID to be retained (of course, this ID will differ in your case).</p>
<p>Now, change the default subvolume of the BTRFS volume to designate the subvolume (snapshot) <i>before-updating</i> and not the root subvolume then reboot:</p>
<pre class="code">#<span class="code_input"> btrfs subvolume set-default 256 /</span>
</pre>
<p>Once the system has rebooted, and if you followed the advice in the previous paragraph that suggests to create an empty file of the same name as the snapshot, you should be able to see if the mounted VFS root is the copy hold by the snapshot <i>before-updating-2011-05-24</i>:</p>
<pre class="code">#<span class="code_input"> ls -l /</span>
...
-rw-rw-rw-   1 root root    0 May 24 20:33 current-is-before-updating-2011-05-24
...
</pre>
<p>The correct subvolume has been used for mounting the VFS! Excellent! This is now the time to mount your &#8220;production&#8221; VFS root (remember the root subvolume can only be accessed via its identification number i.e <i>0</i>):</p>
<pre class="code">#<span class="code_input"> mount -o subvolid=0 /mnt</span>
#<span class="code_input"> mount</span>
...
/dev/sda2 on /mnt type btrfs (rw,subvolid=0)
</pre>
<p>Oh by the way, as the root subvolume is now mounted in <tt>/mnt</tt> let&#8217;s try something, just for the sake of the demonstration:</p>
<pre class="code">#<span class="code_input"> ls /mnt</span>
...
drwxr-xr-x   1 root root    0 May 24 20:33 current-is-before-updating-2011-05-24
...
#<span class="code_input"> btrfs subvolume list /mnt</span>
ID 256 top level 5 path before-updating-2011-05-24
</pre>
<p>No doubt possible <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Time to rollback! For this <b>rsync</b> will be used in the following way:</p>
<pre class="code">#<span class="code_input"> rsync --progress -aHAX --exclude=/proc --exclude=/dev --exclude=/sys --exclude=/mnt / /mnt</span>
</pre>
<p>Basically we are asking rsync to:</p>
<ul>
<li>preserve timestamps, hard and symbolic links, owner/group IDs, ACLs and any extended attributes (refer to the rsync manual page for further details on options used) and to report its progression</li>
<li>ignore the mount points where virtual filesystems are mounted (procfs, sysfs&#8230;)</li>
<li>avoid a re-recursion by reprocessing /mnt (you can speed up the process by adding some extra directories if you are sure they don&#8217;t hold any important changes or any change at all like /var/tmp/portage for example).</li>
</ul>
<p>Be patient! The resync may take several minutes or hours depending on the amount of data amount to process&#8230;</p>
<p>Once finished, you will have to set the default subvolume to be the root subvolume:</p>
<pre class="code">#<span class="code_input"> btrfs subvolume set-default 0 /mnt</span>
ID 256 top level 5 path before-updating-2011-05-24
</pre>
<div class="bs-callout bs-callout-danger">
<div class="bs-head">Warning</div>
<p><b>DO NOT ENTER / instead of /mnt in the above command; it won&#8217;t work and you will be under the snapshot before-updating-2011-05-24 the next time the machine reboots.</b></p>
<p>The reason is that subvolume number must be &#8220;visible&#8221; from the path given at the end of the <b>btrfs subvolume set-default</b> command line. Again refer the boxes analogy: in our context we are in a subbox numbered 256 which is located *inside* the box numbered 0 (so it can&#8217;t see neither interfere with it). [TODO: better explain]</p>
</div>
<p>Now just reboot and you should be in business again! Once you have rebooted just check if you are really under the right subvolume:</p>
<pre class="code">#<span class="code_input"> ls / </span>
...
drwxr-xr-x   1 root root    0 May 24 20:33 current-is-before-updating-2011-05-24
...
#<span class="code_input"> btrfs subvolume list /</span>
ID 256 top level 5 path before-updating-2011-05-24
</pre>
<p>At the right place? Excellent! You can now delete the snapshot if you wish, or better: keep it as a lifeboat of &#8220;last good known system state.&#8221;</p>
<h3><span id="Way_.232:_Change_the_kernel_command_line_in_the_bootloader_configuration_files" class="mw-headline">Way #2: Change the kernel command line in the bootloader configuration files</span></h3>
<p>First search for the newly created subvolume number:</p>
<pre class="code">#<span class="code_input"> btrfs subvolume list / </span>
'''ID 256''' top level 5 path before-updating-2011-05-24
</pre>
<p>&#8216;256&#8217; is the ID to be retained (can differ in your case).</p>
<p>Now with your favourite text editor, edit the adequate kernel command line in your bootloader configuration (<tt>/etc/boot.conf</tt>). This file contains is typically organized in several sections (one per kernel present on the system plus some global settings), like the excerpt below:</p>
<pre>set timeout=5
set default=0

# Production kernel
menuentry "Funtoo Linux production kernel (2.6.39-gentoo x86/64)" {
   insmod part_msdos
   insmod ext2
   ...
   set root=(hd0,1)
   linux /kernel-x86_64-2.6.39-gentoo root=/dev/sda2 
   initrd /initramfs-x86_64-2.6.39-gentoo
}
...
</pre>
<p>Find the correct kernel line and add one of the following statements after root=/dev/sdX:</p>
<pre>rootflags=subvol=before-updating-2011-05-24
   - Or -
rootflags=subvolid=256
</pre>
<div class="bs-callout bs-callout-danger">
<div class="bs-head">Warning</div>
<p>If the kernel your want to use has been generated with Genkernel, you <b>MUST</b> use <i>real_rootflags=subvol=</i>&#8230; instead of <i>rootflags=subvol</i>=&#8230; at the penalty of not having your rootflags taken into consideration by the kernel on reboot.</p>
</div>
<p>Applied to the previous example you will get the following if you referred the subvolume by its name:</p>
<pre>set timeout=5
set default=0

# Production kernel
menuentry "Funtoo Linux production kernel (2.6.39-gentoo x86/64)" {
   insmod part_msdos
   insmod ext2
   ...
   set root=(hd0,1)
   linux /kernel-x86_64-2.6.39-gentoo root=/dev/sda2 rootflags=subvol=before-updating-2011-05-24
   initrd /initramfs-x86_64-2.6.39-gentoo
}
...
</pre>
<p>Or you will get the following if you referred the subvolume by its identification number:</p>
<pre>set timeout=5
set default=0

# Production kernel
menuentry "Funtoo Linux production kernel (2.6.39-gentoo x86/64)" {
   insmod part_msdos
   insmod ext2
   ...
   set root=(hd0,1)
   linux /kernel-x86_64-2.6.39-gentoo root=/dev/sda2 rootflags=subvolid=256
   initrd /initramfs-x86_64-2.6.39-gentoo
}
...
</pre>
<p>Once the modifications are done, save your changes and take the necessary extra steps to commit the configuration changes on the first sectors of the disk if needed (this mostly applies to the users of LILO; Grub and SILO do not need to be refreshed) and reboot.</p>
<p>Once the system has rebooted and if you followed the advice in the previous paragraph that suggests to create an empty file of the same name as the snapshot, you should be able to see if the mounted VFS root is the copy hold by the snapshot <i>before-updating-2011-05-24</i>:</p>
<pre class="code">#<span class="code_input"> ls -l /</span>
...
-rw-rw-rw-   1 root root    0 May 24 20:33 current-is-before-updating-2011-05-24
...
</pre>
<p>The correct subvolume has been used for mounting the VFS! Excellent! This is now the time to mount your &#8220;production&#8221; VFS root (remember the root subvolume can only be accessed via its identification number 0):</p>
<pre class="code">#<span class="code_input"> mount -o subvolid=0 /mnt</span>
#<span class="code_input"> mount</span>
...
/dev/sda2 on /mnt type btrfs (rw,subvolid=0)
</pre>
<p>Time to rollback! For this <b>rsync</b> will be used in the following way:</p>
<pre class="code">#<span class="code_input"> rsync --progress -aHAX --exclude=/proc --exclude=/dev --exclude=/sys --exclude=/mnt / /mnt</span>
</pre>
<p>Here, please refer to what has been said in <a title="BTRFS Fun" href="https://www.funtoo.org/BTRFS_Fun#Way_.231:_Fiddle_with_the_default_subvolume_number">Way #1</a> concerning the used options in rsync. Once everything is in place again, edit your bootloader configuration to remove the rootflags/real_rootflags kernel parameter, reboot and check if you are really under the right subvolume:</p>
<pre class="code">#<span class="code_input"> ls / </span>
...
drwxr-xr-x   1 root root    0 May 24 20:33 current-is-before-updating-2011-05-24
...
#<span class="code_input"> btrfs subvolume list /</span>
ID 256 top level 5 path current-is-before-updating-2011-05-24
</pre>
<p>At the right place? Excellent! You can now delete the snapshot if you wish, or better: keep it as a lifeboat of &#8220;last good known system state.&#8221;</p>
<h1><span id="Some_BTRFS_practices_.2F_returns_of_experience_.2F_gotchas" class="mw-headline">Some BTRFS practices / returns of experience / gotchas</span></h1>
<ul>
<li>Although BTRFS is still evolving, at the date of writing it (still) is <b>an experimental filesystem and should be not be used for production systems and for storing critical data</b> (even if the data is non critical, having backups on a partition formatted with a &#8220;stable&#8221; filesystem like Reiser or ext3/4 is recommended).</li>
<li>From time to time some changes are brought to the metadata (BTRFS format is not definitive at date of writing) and a BTRFS partition could not be used with older Linux kernels (this happened with Linux 2.6.31).</li>
<li>More and more Linux distributions are proposing the filesystem as an alternative for ext4</li>
<li>Some reported gotchas: <a class="external free" href="https://btrfs.wiki.kernel.org/index.php/Gotchas">https://btrfs.wiki.kernel.org/index.php/Gotchas</a></li>
<li>Playing around with BTFRS can be a bit tricky especially when dealing with default volumes and mount point (again: the box analogy)</li>
<li>Using compression (e.g. LZO =&gt;&gt; mount -o compress=lzo) on the filesystem can improve the throughput performance, however many files nowadays are already compressed at application level (music, pictures, videos&#8230;.).</li>
<li>Using space caching capabilities (mount -o space_cache) seems to brings some extra slight performance improvements.</li>
<li>There is very <a class="external text" href="https://lkml.org/lkml/2010/6/18/144">interesting discussion on BTRFS design limitations with B-Trees</a> lying on LKML. We <i>strongly</i> encourage you to read about on</li>
</ul>
<h2><span id="Deploying_a_Funtoo_instance_in_a_subvolume_other_than_the_root_subvolume" class="mw-headline">Deploying a Funtoo instance in a subvolume other than the root subvolume</span></h2>
<p>Some Funtoo core devs have used BTRFS for many months and no major glitches have been reported so far (except an non-aligned memory access trap on SPARC64 in a checksum calculation routine; minor latest kernels may brought a correction) except a long time ago but this was more related to a kernel crash due to a bug that corrupted some internal data rather than the filesystem code in itself.</p>
<p>The following can simplify your life in case of recovery <b>(not tested)</b>:</p>
<p>When you prepare the disk space that will hold the root of your future Funtoo instance (and so, will hold /usr /bin /sbin /etc etc&#8230;), don&#8217;t use the root subvolume but take an extra step to define a subvolume like illustrated below:</p>
<pre class="code">#<span class="code_input"> fdisk /dev/sda2</span>
....
#<span class="code_input"> mkfs.btrfs /dev/sda2</span>
#<span class="code_input"> mount /dev/sda2 /mnt/funtoo</span>
#<span class="code_input"> subvolume create /mnt/funtoo /mnt/funtoo/live-vfs-root-20110523</span>
#<span class="code_input"> chroot /mnt/funtoo/live-vfs-root-20110523 /bin/bash</span>
</pre>
<p>Then either:</p>
<ul>
<li>Set the default subvolume /live-vfs-root-20110523 as being the default subvolume (btrfs subvolume set-default&#8230;. remember to inspect the subvolume identification number)</li>
<li>Use rootflag / real_rootfsflags (always use real_rootfsflags for kernel generated with Genkernel) on the kernel command line in your bootloader configuration file</li>
</ul>
<p>Technically speaking, it won&#8217;t change your life BUT at system recovery: when you want to rollback to a functional VFS root copy because something happened (buggy system package, too aggressive cleanup that removed Python, dead compiling toolchain&#8230;) you can avoid a time costly rsync but at the cost of putting a bit of overhead over your shoulders when taking a snapshot.</p>
<p>Here again you have two ways to recover the system:</p>
<ul>
<li><b>fiddling with the default subvolume:</b>
<ul>
<li>Mount to the no named volume somewhere (e.g. <b>mount -o subvolid=0 /dev/sdX /mnt</b>)</li>
<li>Take a snapshot (remember to check its identification number) of your current subvolume and store it under the root volume you just have just mounted (<b>btrfs snapshot create / /mnt/before-updating-20110524</b>) &#8212; (Where is the &#8220;frontier&#8221;? If 0 is monted does its contennts also appear in the taken snashot located on the same volume?)</li>
<li>Update your system or do whatever else &#8220;dangerous&#8221; operation</li>
<li>If you need to return to the latest good known system state, just set the default subvolume to use to the just taken snapshot (<b>btrfs subvolume set-default <i>&lt;snapshotnumber here&gt;</i> /mnt</b>)</li>
<li>Reboot</li>
<li>Once you have rebooted, just mount the root subvolume again and delete the subvolume that correspond to the failed system update (<b>btrfs subvolume delete /mnt/&lt;buggy VFS rootsnapshot name here&gt;</b>)</li>
</ul>
</li>
</ul>
<ul>
<li><b>fiddling with the kernel command line:</b>
<ul>
<li>Mount to the no named volume somewhere (e.g. <b>mount -o subvolid=0 /dev/sdX /mnt</b>)</li>
<li>Take a snapshot (remember to check its identification number) of your current subvolume and store it under the root volume you just have just mounted (<b>btrfs snapshot create / /mnt/before-updating-20110524</b>) &#8212; (Where is the &#8220;frontier&#8221;? If 0 is mounted does its contents also appear in the taken snapshot located on the same volume?)</li>
<li>Update your system or do whatever else &#8220;dangerous&#8221; operation</li>
<li>If you need to return to the latest good known system state, just set the rootflags/real_rootflags as demonstrated in previous paragraphs in your loader configuration file</li>
<li>Reboot</li>
<li>Once you have rebooted, just mount the root subvolume again and delete the subvolume that correspond to the failed system update (<b>btrfs subvolume delete /mnt/&lt;buggy VFS rootsnapshot name here&gt;</b>)</li>
</ul>
</li>
</ul>
<h2><span id="Space_recovery_.2F_defragmenting_the_filesystem" class="mw-headline">Space recovery / defragmenting the filesystem</span></h2>
<div class="bs-callout bs-callout-info">
<div class="bs-head">Tip</div>
<p>From time to time it is advised to ask for re-optimizing the filesystem structures and data blocks in a subvolume. In BTRFS terminology this is called a defragmentation and it only be performed when the subvolume is mounted in the VFS (online defragmentation):</p>
</div>
<pre class="code">#<span class="code_input"> btrfs filesystem defrag /mnt</span>
</pre>
<p>You can still access the subvolume, even change its contents, while a defragmentation is running.</p>
<p>It is also a good idea to remove the snapshots you don&#8217;t use anymore especially if huge files and/or lots of files are changed because snapshots will still hold some blocks that could be reused.</p>
<h2><span id="SSE_4.2_boost" class="mw-headline">SSE 4.2 boost</span></h2>
<p>If your CPU supports hardware calculation of CRC32 (e.g. since Intel Nehalem series and later and AMD Bulldozer series), you are encouraged to enable that support in your kernel since BTRFS makes an aggressive use of those. Just check you have enabled <i>CRC32c INTEL hardware acceleration</i> in <i>Cryptographic API</i> either as a module or as a built-in feature</p>
<h1><span id="Recovering_an_apparent_dead_BTRFS_filesystem" class="mw-headline">Recovering an apparent dead BTRFS filesystem</span></h1>
<p>Dealing with a filesystem metadata coherence is a critical in a filesystem design. Losing some data blocks (i.e. having some corrupted files) is less critical than having a screwed-up and unmountable filesystem especially if you do backups on a regular basis <b>(the rule with BTRFS is *do backups*, BTRFS has no mature filesystem repair tool and you *will* end up in having to re-create your filesystem from scratch again sooner or later).</b></p>
<h2><span id="Mounting_with_recovery_option_.28Linux_3.2_and_beyond.29" class="mw-headline">Mounting with recovery option (Linux 3.2 and beyond)</span></h2>
<p>If you are using <b>Linux 3.2 and later (only!)</b>, you can use the <i>recovery</i> option to make BTRFS seek for a usable copy of tree root (several copies of it exists on the disk). Just mount your filesystem as:</p>
<pre class="code">#<span class="code_input"> mount -o recovery /dev/yourBTFSvolume /mount/point</span>
</pre>
<h2><span id="btrfs-select-super_.2F_btrfs-zero-log" class="mw-headline">btrfs-select-super / btrfs-zero-log</span></h2>
<p>Two other handy tools exist but they are not deployed by default by <i>sys-fs/btrfs-progs</i> (even <i>btrfs-progs-9999</i>) ebuilds because they only lie in the branch <i>&#8220;next&#8221;</i> of the<i> btrfs-progs</i> Git repository:</p>
<ul>
<li>btrfs-select-super</li>
<li>btrfs-zero-log</li>
</ul>
<h3><span id="Building_the_btrfs-progs_goodies" class="mw-headline">Building the btrfs-progs goodies</span></h3>
<p>The two tools this section is about are not build by default and Funtoo ebuilds does not build them as well for the moment. So you must build them manually:</p>
<pre class="code">#<span class="code_input"> mkdir ~/src</span>
#<span class="code_input"> cd ~/src</span>
#<span class="code_input"> git clone git://git.kernel.org/pub/scm/linux/kernel/git/mason/btrfs-progs.git </span>
#<span class="code_input"> cd btrfs-progs</span>
#<span class="code_input"> make &amp;&amp; make btrfs-select-super &amp;&amp; make btrfs-zero-log</span>
</pre>
<div class="bs-callout bs-callout-info">
<div class="bs-head">Note</div>
<p>In the past, <i>btrfs-select-super</i> and <i>btrfs-zero-log</i> were lying in the git-next branch, this is no longer the case and those tools are available in the master branch</p>
</div>
<h3><span id="Fixing_dead_superblock" class="mw-headline">Fixing dead superblock</span></h3>
<p>In case of a corrupted superblock, start by asking btrfsck to use an alternate copy of the superblock instead of the superblock #0. This is achieved via the -s option followed by the number of the alternate copy you wish to use. In the following example we ask for using the superblock copy #2 of /dev/sda7:</p>
<pre class="code">#<span class="code_input"> ./btrfsck --s 2 /dev/sd7</span>
</pre>
<p>When btrfsck is happy, use btrfs-super-select to restore the default superblock (copy #0) with a clean copy. In the following example we ask for restoring the superblock of /dev/sda7 with its copy #2:</p>
<pre class="code">#<span class="code_input"> ./btrfs-super-select -s 2  /dev/sda7</span>
</pre>
<p>Note that this will overwrite all the other supers on the disk, which means you really only get one shot at it.</p>
<p><b>If you run btrfs-super-select prior prior to figuring out which one is good, you&#8217;ve lost your chance to find a good one.</b></p>
<h3><span id="Clearing_the_BTRFS_journal" class="mw-headline">Clearing the BTRFS journal</span></h3>
<p><b> This will only help with one specific problem! </b></p>
<p>If you are unable to mount a BTRFS partition after a hard shutdown, crash or power loss, it may be due to faulty log playback in kernels prior to 3.2. The first thing to try is updating your kernel, and mounting. If this isn&#8217;t possible, an alternate solution lies in truncating the BTRFS journal, but only if you see &#8220;replay_one_*&#8221; functions in the oops callstack.</p>
<p>To truncate the journal of a BTRFS partition (and thereby lose any changes that only exist in the log!), just give the filesystem to process to <i>btrfs-zero-log</i>:</p>
<pre class="code">#<span class="code_input"> ./btrfs-zero-log /dev/sda7</span>
</pre>
<p>This is not a generic technique, and works by permanently throwing away a small amount of potentially good data.</p>
<h2><span id="Using_btrfsck" class="mw-headline">Using btrfsck</span></h2>
<div class="bs-callout bs-callout-danger">
<div class="bs-head">Warning</div>
<p>Extremely experimental&#8230;</p>
</div>
<p>If one thing is famous in the BTRFS world it would be the so-wished fully functional <i>btrfsck</i>. A read-only version of the tool was existing out there for years, however at the begining of 2012, BTRFS developers made a public and very experimental release: the secret jewel lies in the branch <i>dangerdonteveruse</i> of the BTRFS Git repository hold by Chris Mason on kernel.org.</p>
<pre class="code">#<span class="code_input"> git clone git://git.kernel.org/pub/scm/linux/kernel/git/mason/btrfs-progs.git</span>
#<span class="code_input"> cd btrfs-progs</span>
#<span class="code_input"> git checkout dangerdonteveruse</span>
#<span class="code_input"> make</span>
</pre>
<p>So far the tool can:</p>
<ul>
<li>Fix errors in the extents tree and in blocks groups accounting</li>
<li>Wipe the CRC tree and create a brand new one (you can to mount the filesystem with CRC checking disabled )</li>
</ul>
<p>To repair:</p>
<pre class="code">#<span class="code_input"> btrfsck --repair /dev/''yourBTRFSvolume''</span>
</pre>
<p>To wipe the CRC tree:</p>
<pre class="code">#<span class="code_input"> btrfsck --init-csum-tree /dev/''yourBTRFSvolume''</span>
</pre>
<p>Two other options exist in the source code: <i>&#8211;super</i> (equivalent of btrfs-select-super ?) and <i>&#8211;init-extent-tree</i> (clears out any extent?)</p>
<h1><span id="Final_words" class="mw-headline">Final words</span></h1>
<p>We give the great lines here but BTRFS can be very tricky especially when several subvolumes coming from several BTRFS volumes are used. And remember: BTRFS is still experimental at date of writing <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2><span id="Lessons_learned" class="mw-headline">Lessons learned</span></h2>
<ul>
<li>Very interesting but still lacks some important features present in ZFS like RAID-Z, virtual volumes, management by attributes, filesystem streaming, etc.</li>
<li>Extremly interesting for Gentoo/Funtoo systems partitions (snapshot/rollback capabilities). However not integrated in portage yet.</li>
<li>If possible, use a file monitoring tool like TripWire this is handy to see what file has been corrupted once the filesystem is recovered or if a bug happens</li>
<li><b>It is highly advised to not use the root subvolume when deploying a new Funtoo instance</b> or put any kind of data on it in a more general case. Rolling back a data snapshot will be much easier and much less error prone (no copy process, just a matter of &#8216;swapping&#8217; the subvolumes).</li>
<li>Backup, backup backup your data! <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></li>
</ul>
<div class="bs-announce bs-announce-main">
<p><a title="Support Funtoo" href="https://www.funtoo.org/Support_Funtoo">Support Funtoo</a> and help us gro</p>
</div>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>在 Linux 上简单模拟系统负载的方法</title>
		<link>https://www.bhzhu203.com/2018/01/22/%e5%9c%a8-linux-%e4%b8%8a%e7%ae%80%e5%8d%95%e6%a8%a1%e6%8b%9f%e7%b3%bb%e7%bb%9f%e8%b4%9f%e8%bd%bd%e7%9a%84%e6%96%b9%e6%b3%95/</link>
		
		<dc:creator><![CDATA[bhzhu203]]></dc:creator>
		<pubDate>Mon, 22 Jan 2018 13:31:25 +0000</pubDate>
				<category><![CDATA[linux知识]]></category>
		<category><![CDATA[14]]></category>
		<category><![CDATA[28]]></category>
		<category><![CDATA[CN]]></category>
		<guid isPermaLink="false">http://www.bhzhu203.com/?p=450</guid>

					<description><![CDATA[编译自：https://bash-prompt.net/guides/creat [&#8230;]]]></description>
										<content:encoded><![CDATA[<div id="header_info" class="h bm bm_c">
<p class="copyright"><span class="z textcut">编译自：<a href="https://bash-prompt.net/guides/create-system-load/" target="_blank" rel="noopener">https://bash-prompt.net/guides/create-system-load/</a></span> <span class="y">作者： Elliot Cooper</span> <br class="clear" /> <span class="z">原创：<a href="https://linux.cn/lctt/" target="_blank" rel="noopener">LCTT</a> <a href="https://linux.cn/article-9235-1.html" target="_blank" rel="noopener">https://linux.cn/article-9235-1.html</a></span> <span class="y">译者： <a href="https://linux.cn/lctt/lujun9972" target="_blank" rel="noopener">DarkSun</a></span> <br class="clear" /> <span class="z">本文地址：<a href="https://linux.cn/article-9235-1.html">https://linux.cn/article-9235-1.html</a></span></p>
<p class="xg1">2018-01-14 10:31</p>
</div>
<div id="diysummarytop" class="area"></div>
<div id="diysummarybottom" class="area"></div>
<div class="d">
<div id="diycontenttop" class="area"></div>
<div id="inner_nav" class="bm">
<div class="bm_h cl">本文导航</div>
<div class="bm_c inner_menu">
<ul class="xl cl">
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-9235-1.html#3_496">CPU</a><span class="y">13%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-9235-1.html#3_1063">内存占用</a><span class="y">28%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-9235-1.html#3_2054">磁盘 I/O</a><span class="y">54%</span></li>
</ul>
</div>
</div>
<div id="ad10" class="linuxcnad"></div>
<div id="article_content" class="bm">
<div class="linuxcnad"></div>
<p>系统管理员通常需要探索在不同负载对应用性能的影响。这意味着必须要重复地人为创造负载。当然，你可以通过专门的工具来实现，但有时你可能不想也无法安装新工具。</p>
<p>每个 Linux 发行版中都自带有创建负载的工具。他们不如专门的工具那么灵活，但它们是现成的，而且无需专门学习。</p>
<p><a id="3_496" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h3 id="toc_1">CPU</h3>
<p>下面命令会创建 CPU 负荷，方法是通过压缩随机数据并将结果发送到 <code>/dev/null</code>：</p>
<ol class="linenums">
<li class="L0"><code><span class="kwd">cat</span> <span class="pun">/</span><span class="pln">dev</span><span class="pun">/</span><span class="pln">urandom </span><span class="pun">|</span><span class="pln"> gzip </span><span class="pun">-</span><span class="lit">9</span> <span class="pun">&gt;</span> <span class="str">/dev/</span><span class="kwd">null</span></code></li>
</ol>
<p>如果你想要更大的负荷，或者系统有多个核，那么只需要对数据进行压缩和解压就行了，像这样：</p>
<ol class="linenums">
<li class="L0"><code><span class="kwd">cat</span> <span class="pun">/</span><span class="pln">dev</span><span class="pun">/</span><span class="pln">urandom </span><span class="pun">|</span><span class="pln"> gzip </span><span class="pun">-</span><span class="lit">9</span> <span class="pun">|</span><span class="pln"> gzip </span><span class="pun">-</span><span class="pln">d </span><span class="pun">|</span><span class="pln"> gzip </span><span class="pun">-</span><span class="lit">9</span> <span class="pun">|</span><span class="pln"> gzip </span><span class="pun">-</span><span class="pln">d </span><span class="pun">&gt;</span> <span class="str">/dev/</span><span class="kwd">null</span></code></li>
</ol>
<p>按下 <code>CTRL+C</code> 来终止进程。</p>
<p><a id="3_1063" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h3 id="toc_2">内存占用</h3>
<p>下面命令会减少可用内存的总量。它是通过在内存中创建文件系统然后往里面写文件来实现的。你可以使用任意多的内存，只需哟往里面写入更多的文件就行了。</p>
<p>首先，创建一个挂载点，然后将 ramfs 文件系统挂载上去：</p>
<ol class="linenums">
<li class="L0"><code><span class="kwd">mkdir</span><span class="pln"> z</span></code></li>
<li class="L1"><code><span class="kwd">mount</span> <span class="pun">-</span><span class="pln">t ramfs ramfs z</span><span class="pun">/</span></code></li>
</ol>
<p>第二步，使用 <code>dd</code> 在该目录下创建文件。这里我们创建了一个 128M 的文件：</p>
<ol class="linenums">
<li class="L0"><code><span class="kwd">dd</span> <span class="kwd">if</span><span class="pun">=</span><span class="str">/dev/</span><span class="pln">zero of</span><span class="pun">=</span><span class="pln">z</span><span class="pun">/</span><span class="kwd">file</span><span class="pln"> bs</span><span class="pun">=</span><span class="lit">1M</span><span class="pln"> count</span><span class="pun">=</span><span class="lit">128</span></code></li>
</ol>
<p>文件的大小可以通过下面这些操作符来修改：</p>
<ul>
<li><code>bs=</code> 块大小。可以是任何数字后面接上 <code>B</code>（表示字节），<code>K</code>（表示 KB），<code>M</code>（ 表示 MB）或者 <code>G</code>（表示 GB）。</li>
<li><code>count=</code> 要写多少个块。</li>
</ul>
<p><a id="3_2054" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h3 id="toc_3">磁盘 I/O</h3>
<p>创建磁盘 I/O 的方法是先创建一个文件，然后使用 <code>for</code> 循环来不停地拷贝它。</p>
<p>下面使用命令 <code>dd</code> 创建了一个全是零的 1G 大小的文件：</p>
<ol class="linenums">
<li class="L0"><code><span class="kwd">dd</span> <span class="kwd">if</span><span class="pun">=</span><span class="str">/dev/</span><span class="pln">zero of</span><span class="pun">=</span><span class="pln">loadfile bs</span><span class="pun">=</span><span class="lit">1M</span><span class="pln"> count</span><span class="pun">=</span><span class="lit">1024</span></code></li>
</ol>
<p>下面命令用 <code>for</code> 循环执行 10 次操作。每次都会拷贝 <code>loadfile</code> 来覆盖 <code>loadfile1</code>：</p>
<ol class="linenums">
<li class="L0"><code><span class="kwd">for</span><span class="pln"> i </span><span class="kwd">in</span> <span class="pun">{</span><span class="lit">1.</span><span class="pun">.</span><span class="lit">10</span><span class="pun">};</span> <span class="kwd">do</span> <span class="kwd">cp</span><span class="pln"> loadfile loadfile1</span><span class="pun">;</span> <span class="kwd">done</span></code></li>
</ol>
<p>通过修改 <code>{1..10}</code> 中的第二个参数来调整运行时间的长短。（LCTT 译注：你的 Linux 系统中的默认使用的 <code>cp</code> 命令很可能是 <code>cp -i</code> 的别名，这种情况下覆写会提示你输入 <code>y</code> 来确认，你可以使用 <code>-f</code> 参数的 <code>cp</code> 命令来覆盖此行为，或者直接用 <code>/bin/cp</code> 命令。）</p>
<p>若你想要一直运行，直到按下 <code>CTRL+C</code> 来停止，则运行下面命令：</p>
<ol class="linenums">
<li class="L0"><code><span class="kwd">while</span> <span class="kwd">true</span><span class="pun">;</span> <span class="kwd">do</span> <span class="kwd">cp</span><span class="pln"> loadfile loadfile1</span><span class="pun">;</span> <span class="kwd">done</span></code></li>
</ol>
<hr />
<p>via: <a class="ext" href="https://bash-prompt.net/guides/create-system-load/" target="_blank" rel="external nofollow noopener">https://bash-prompt.net/guides/create-system-load/</a></p>
<p>作者：<a class="ext" href="https://bash-prompt.net" target="_blank" rel="external nofollow noopener">Elliot Cooper</a> 译者：<a class="ext" href="https://github.com/lujun9972" target="_blank" rel="external nofollow noopener">lujun9972</a> 校对：<a class="ext" href="https://github.com/wxy" target="_blank" rel="external nofollow noopener">wxy</a></p>
<p>本文由 <a class="ext" href="https://github.com/LCTT/TranslateProject" target="_blank" rel="external nofollow noopener">LCTT</a> 原创编译，<a href="https://linux.cn/article-9235-1.html?utm_source=index&amp;utm_medium=more">Linux中国</a> 荣誉推出</p>
</div>
</div>
<div id="footer_info" class="h bm_c bm">
<p class="copyright"><span class="z textcut">编译自：<a href="https://bash-prompt.net/guides/create-system-load/" target="_blank" rel="noopener">https://bash-prompt.net/guides/create-system-load/</a></span> <span class="y">作者： Elliot Cooper</span> <br class="clear" /> <span class="z">原创：<a href="https://linux.cn/lctt/" target="_blank" rel="noopener">LCTT</a> <a href="https://linux.cn/article-9235-1.html" target="_blank" rel="noopener">https://linux.cn/article-9235-1.html</a></span> <span class="y">译者： lujun9972</span> <br class="clear" /><br />
本文由 LCTT 原创翻译，<a href="https://linux.cn/article-9235-1.html">Linux中国首发</a>。也想加入译者行列，为开源做一些自己的贡献么？欢迎加入 <a href="http://lctt.github.io/" target="_blank" rel="noopener">LCTT</a>！<br />
翻译工作和译文发表仅用于学习和交流目的，翻译工作遵照 <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" target="_blank" rel="noopener">CC-BY-NC-SA 协议规定</a>，如果我们的工作有侵犯到您的权益，请及时联系我们。 <br class="clear" /> 欢迎遵照 <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" target="_blank" rel="noopener">CC-BY-NC-SA 协议规定</a>转载，敬请在正文中标注并保留原文/译文链接和作者/译者等信息。 <br class="clear" /> 文章仅代表作者的知识和看法，如有不同观点，请楼下排队<a>吐槽</a> <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f600.png" alt="😀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Bash 脚本：正则表达式基础篇</title>
		<link>https://www.bhzhu203.com/2017/12/28/bash-%e8%84%9a%e6%9c%ac%ef%bc%9a%e6%ad%a3%e5%88%99%e8%a1%a8%e8%be%be%e5%bc%8f%e5%9f%ba%e7%a1%80%e7%af%87/</link>
		
		<dc:creator><![CDATA[bhzhu203]]></dc:creator>
		<pubDate>Thu, 28 Dec 2017 13:11:47 +0000</pubDate>
				<category><![CDATA[linux知识]]></category>
		<category><![CDATA[70]]></category>
		<category><![CDATA[CN]]></category>
		<category><![CDATA[HTTPS]]></category>
		<guid isPermaLink="false">http://www.bhzhu203.com/?p=448</guid>

					<description><![CDATA[原创：LCTT https://linux.cn/article-9182-1. [&#8230;]]]></description>
										<content:encoded><![CDATA[<div id="header_info" class="h bm bm_c">
<p class="copyright"><br class="clear" /> <span class="z">原创：<a href="https://linux.cn/lctt/" target="_blank" rel="noopener">LCTT</a> <a href="https://linux.cn/article-9182-1.html" target="_blank" rel="noopener">https://linux.cn/article-9182-1.html</a></span> <span class="y">译者： <a href="https://linux.cn/lctt/kimii" target="_blank" rel="noopener">kimii</a></span> <br class="clear" /> <span class="z">本文地址：<a href="https://linux.cn/article-9182-1.html">https://linux.cn/article-9182-1.html</a></span></p>
<p class="xg1">2017-12-27 15:11    收藏: <em id="_favtimes">1</em></p>
</div>
<div id="diysummarytop" class="area"></div>
<div id="diysummarybottom" class="area"></div>
<div class="d">
<div id="diycontenttop" class="area"></div>
<div id="inner_nav" class="bm">
<div class="bm_h cl">本文导航</div>
<div class="bm_c inner_menu">
<ul class="xl cl">
<li><span class="folder"><a>&#8211;</a></span><a href="https://linux.cn/article-9182-1.html#3_2078">基础的正则表示式</a><span class="y">23%</span>
<ul class="xl cl">
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-9182-1.html#4_3172">. （点）</a><span class="y">35%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-9182-1.html#4_3837">[ ]</a><span class="y">43%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-9182-1.html#4_4458">[^ ]</a><span class="y">50%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-9182-1.html#4_5511">* (星号)</a><span class="y">62%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-9182-1.html#4_5834">+</a><span class="y">66%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-9182-1.html#4_6225">?</a><span class="y">70%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-9182-1.html#4_6513">非常重要的提示</a><span class="y">73%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-9182-1.html#4_7542">\</a><span class="y">85%</span></li>
</ul>
</li>
</ul>
</div>
</div>
<div id="ad10" class="linuxcnad"></div>
<div id="article_content" class="bm">
<div class="linuxcnad"></div>
<p><ruby>正则表达式<rt>Regular expressions</rt></ruby>（简写为 regex 或者 regexp）基本上是定义一种搜索模式的字符串，可以被用来执行“搜索”或者“搜索并替换”操作，也可以被用来验证像密码策略等条件。</p>
<p>正则表达式是一个我们可利用的非常强大的工具，并且使用正则表达式的优点是它能在几乎所有计算机语言中被使用。所以如果你使用 Bash 脚本或者创建一个 python 程序时，我们可以使用正则表达式，或者也可以写一个单行搜索查询。</p>
<p>在这篇教程中，我们将会学习一些正则表达式的基本概念，并且学习如何在 Bash 中通过 <code>grep</code> 使用它们，但是如果你希望在其他语言如 python 或者 C 中使用它们，你只能使用正则表达式部分。那么让我们通过正则表达式的一个例子开始吧，</p>
<p>正则表达式看起来像 <code>/t[aeiou]l/</code> 这个样子。</p>
<p>但这是什么意思呢？它意味着所提到的正则表达式将寻找一个词，它以 <code>t</code> 开始，在中间包含字母 <code>a e i o u</code> 中任意一个，并且字母 <code>l</code> 最为最后一个字符。它可以是 <code>tel</code>，<code>tal</code> 或者 <code>til</code>，可以匹配一个单独的词或者其它单词像 <code>tilt</code>，<code>brutal</code> 或者 <code>telephone</code> 的一部分。</p>
<p>grep 使用正则表达式的语法是 <code>$ grep "regex_search_term" file_location</code></p>
<p>如果不理解，不要担心，这只是一个例子，来展示可以利用正则表达式获取什么，相信我，这是最简单的例子。我们可以从正则表达式中获取更多。现在我们将从正则表达式基础的开始。</p>
<ul>
<li>推荐阅读: <a class="ext" href="http://linuxtechlab.com/useful-linux-commands-you-should-know/" target="_blank" rel="external nofollow noopener">你应该知道的有用的 linux 命令</a></li>
</ul>
<p><a id="3_2078" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h3 id="toc_1">基础的正则表示式</h3>
<p>现在我们开始学习一些被称为<ruby>元字符<rt>MetaCharacters</rt></ruby>的特殊字符。它们可以帮助我们创建更复杂的正则表达式搜索项。下面提到的是基本元字符的列表，</p>
<ul>
<li><code>.</code> 点将匹配任意字符</li>
<li><code>[ ]</code> 将匹配一个字符范围</li>
<li><code>[^ ]</code> 将匹配除了括号中提到的那个之外的所有字符</li>
<li><code>*</code> 将匹配零个或多个前面的项</li>
<li><code>+</code> 将匹配一个或多个前面的项</li>
<li><code>?</code> 将匹配零个或一个前面的项</li>
<li><code>{n}</code> 将匹配 n 次前面的项</li>
<li><code>{n,}</code> 将匹配 n 次或更多前面的项</li>
<li><code>{n,m}</code> 将匹配在 n 和 m 次之间的项</li>
<li><code>{,m}</code> 将匹配少于或等于 m 次的项</li>
<li><code>\</code> 是一个转义字符，当我们需要在我们的搜索中包含一个元字符时使用</li>
</ul>
<p>现在我们将用例子讨论所有这些元字符。</p>
<p><a id="4_3172" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="toc_2"><code>.</code> （点）</h4>
<p>它用于匹配出现在我们搜索项中的任意字符。举个例子，我们可以使用点如：</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">grep</span> <span class="str">"d.g"</span><span class="pln"> file1</span></code></li>
</ol>
<p>这个正则表达式意味着我们在名为 ‘file1’ 的文件中查找的词以 <code>d</code> 开始，以 <code>g</code>结尾，中间可以有 1 个字符的字符串。同样，我们可以使用任意数量的点作为我们的搜索模式，如 <code>T......h</code>，这个查询项将查找一个词，以 <code>T</code> 开始，以 <code>h</code> 结尾，并且中间可以有任意 6 个字符。</p>
<p><a id="4_3837" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="toc_3"><code>[ ]</code></h4>
<p>方括号用于定义字符范围。例如，我们需要搜索一些特别的单词而不是匹配任何字符，</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">grep</span> <span class="str">"N[oen]n"</span><span class="pln"> file2</span></code></li>
</ol>
<p>这里，我们正寻找一个单词，以 <code>N</code>开头，以 <code>n</code> 结尾，并且中间只能有 <code>o</code>、<code>e</code> 或者 <code>n</code> 中的一个。 在方括号中我们可以提到单个到任意数量的字符。</p>
<p>我们在方括号中也可以定义像 <code>a-e</code>或者 <code>1-18</code> 作为匹配字符的列表。</p>
<p><a id="4_4458" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="toc_4"><code>[^ ]</code></h4>
<p>这就像正则表达式的 not 操作。当使用 <code>[^ ]</code> 时，它意味着我们的搜索将包括除了方括号内提到的所有字符。例如，</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">grep</span> <span class="str">"St[^1-9]d"</span><span class="pln"> file3</span></code></li>
</ol>
<p>这意味着我们可以拥有所有这样的单词，它们以 <code>St</code> 开始，以字母 <code>d</code> 结尾，并且不得包含从 <code>1</code> 到 <code>9</code> 的任何数字。</p>
<p>到现在为止，我们只使用了仅需要在中间查找单个字符的正则表达式的例子，但是如果我们需要更多字符该怎么办呢。假设我们需要找到以一个字符开头和结尾的所有单词，并且在中间可以有任意数量的字符。这就是我们使用乘数元字符如 <code>+</code> <code>*</code> 与 <code>?</code> 的地方。</p>
<p><code>{n}</code>、<code>{n,m}</code>、<code>{n,}</code> 或者 <code>{,m}</code> 也是可以在我们的正则表达式项中使用的其他乘数元字符。</p>
<p><a id="4_5511" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="toc_5"><code>*</code> (星号)</h4>
<p>以下示例匹配字母 <code>k</code> 的任意出现次数，包括一次没有：</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">grep</span> <span class="str">"lak*"</span><span class="pln"> file4</span></code></li>
</ol>
<p>它意味着我们可以匹配到 <code>lake</code>、<code>la</code> 或者 <code>lakkkk</code>。</p>
<p><a id="4_5834" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="toc_6"><code>+</code></h4>
<p>以下模式要求字符串中的字母 <code>k</code> 至少被匹配到一次：</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">grep</span> <span class="str">"lak+"</span><span class="pln"> file5</span></code></li>
</ol>
<p>这里 <code>k</code> 在我们的搜索中至少需要发生一次，所以我们的结果可以为 <code>lake</code> 或者 <code>lakkkk</code>，但不能是 <code>la</code>。</p>
<p><a id="4_6225" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="toc_7"><code>?</code></h4>
<p>在以下模式匹配中</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">grep</span> <span class="str">"ba?b"</span><span class="pln"> file6</span></code></li>
</ol>
<p>匹配字符串 <code>bb</code> 或 <code>bab</code>，使用 <code>?</code> 乘数，我们可以有一个或零个字符的出现。</p>
<p><a id="4_6513" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="toc_8">非常重要的提示</h4>
<p>当使用乘数时这是非常重要的，假设我们有一个正则表达式</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">grep</span> <span class="str">"S.*l"</span><span class="pln"> file7</span></code></li>
</ol>
<p>我们得到的结果是 <code>small</code>、<code>silly</code>，并且我们也得到了 <code>Shane is a little to play ball</code>。但是为什么我们得到了 <code>Shane is a little to play ball</code>？我们只是在搜索中寻找单词，为什么我们得到了整个句子作为我们的输出。</p>
<p>这是因为它满足我们的搜索标准，它以字母 <code>s</code> 开头，中间有任意数量的字符并以字母 <code>l</code> 结尾。那么，我们可以做些什么来纠正我们的正则表达式来只是得到单词而不是整个句子作为我们的输出。</p>
<p>我们在正则表达式中需要增加 <code>?</code> 元字符，</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">grep</span> <span class="str">"S.*?l"</span><span class="pln"> file7</span></code></li>
</ol>
<p>这将会纠正我们正则表达式的行为。</p>
<h4 id="toc_9"><code>\</code></h4>
<p><code>\</code> 是当我们需要包含一个元字符或者对正则表达式有特殊含义的字符的时候来使用。例如，我们需要找到所有以点结尾的单词，所以我们可以使用：</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">grep</span> <span class="str">"S.*\\."</span><span class="pln"> file8</span></code></li>
</ol>
<p>这将会查找和匹配所有以一个点字符结尾的词。</p>
<p>通过这篇基本正则表达式教程，我们现在有一些关于正则表达式如何工作的基本概念。在我们的下一篇教程中，我们将学习一些高级的正则表达式的概念。同时尽可能多地练习，创建正则表达式并试着尽可能多的在你的工作中加入它们。如果有任何疑问或问题，您可以在下面的评论区留言。</p>
<hr />
<p>via: <a class="ext" href="http://linuxtechlab.com/bash-scripting-learn-use-regex-basics/" target="_blank" rel="external nofollow noopener">http://linuxtechlab.com/bash-scripting-learn-use-regex-basics/</a></p>
<p>作者：<a class="ext" href="http://linuxtechlab.com/author/shsuain/" target="_blank" rel="external nofollow noopener">SHUSAIN</a> 译者：<a class="ext" href="https://github.com/kimii" target="_blank" rel="external nofollow noopener">kimii</a> 校对：<a class="ext" href="https://github.com/wxy" target="_blank" rel="external nofollow noopener">wxy</a></p>
<p>本文由 <a class="ext" href="https://github.com/LCTT/TranslateProject" target="_blank" rel="external nofollow noopener">LCTT</a> 原创编译，<a href="https://linux.cn/article-9182-1.html">Linux中国</a> 荣誉推出</p>
</div>
</div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>vim 神器的打造方式</title>
		<link>https://www.bhzhu203.com/2017/10/25/vim-%e7%a5%9e%e5%99%a8%e7%9a%84%e6%89%93%e9%80%a0%e6%96%b9%e5%bc%8f/</link>
		
		<dc:creator><![CDATA[bhzhu203]]></dc:creator>
		<pubDate>Wed, 25 Oct 2017 10:52:12 +0000</pubDate>
				<category><![CDATA[linux知识]]></category>
		<category><![CDATA[14]]></category>
		<category><![CDATA[25]]></category>
		<category><![CDATA[64]]></category>
		<guid isPermaLink="false">http://www.bhzhu203.com/?p=446</guid>

					<description><![CDATA[转载自：SF https://segmentfault.com/a/119000 [&#8230;]]]></description>
										<content:encoded><![CDATA[<div id="header_info" class="h bm bm_c">
<p class="copyright"><span class="z textcut">转载自：SF <a href="https://segmentfault.com/a/1190000011466454" target="_blank" rel="noopener">https://segmentfault.com/a/1190000011466454</a></span> <span class="y">作者： 枫上雾棋</span> <br class="clear" /> <span class="z">本文地址：<a href="https://linux.cn/article-8997-1.html">https://linux.cn/article-8997-1.html</a></span></p>
<p class="xg1">2017-10-24 18:40    收藏: <em id="_favtimes">4</em></p>
</div>
<div id="diysummarytop" class="area"></div>
<div id="diysummarybottom" class="area"></div>
<div class="d">
<div id="diycontenttop" class="area"></div>
<div id="inner_nav" class="bm">
<div class="bm_h cl">本文导航</div>
<div class="bm_c inner_menu">
<ul class="xl cl">
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#3_463">安装</a><span class="y">03%</span></li>
<li><span class="folder"><a>&#8211;</a></span><a href="https://linux.cn/article-8997-1.html#3_573">新手指南</a><span class="y">04%</span>
<ul class="xl cl">
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_787">移动光标</a><span class="y">05%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_1088">退出</a><span class="y">08%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_1190">删除</a><span class="y">08%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_1386">修改</a><span class="y">10%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_1520">撤销</a><span class="y">11%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_1587">复制粘贴剪切</a><span class="y">11%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_1709">状态</a><span class="y">12%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_1787">查找</a><span class="y">13%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_2047">替换</a><span class="y">15%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_2203">折叠</a><span class="y">16%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_2311">执行外部命令</a><span class="y">17%</span></li>
</ul>
</li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#3_2379">.vimrc</a><span class="y">17%</span></li>
<li><span class="folder"><a>&#8211;</a></span><a href="https://linux.cn/article-8997-1.html#3_3047">基本配置</a><span class="y">22%</span>
<ul class="xl cl">
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_3070">取消备份</a><span class="y">22%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_3155">文件编码</a><span class="y">23%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_3230">显示行号</a><span class="y">23%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_3297">取消换行</a><span class="y">24%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_3364">显示光标当前位置</a><span class="y">24%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_3442">设置缩进</a><span class="y">25%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_3543">突出显示当前行</a><span class="y">26%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_3623">查找</a><span class="y">26%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_3697">左下角显示当前 vim 模式</a><span class="y">27%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_3786">代码折叠</a><span class="y">28%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_3895">主题</a><span class="y">28%</span></li>
</ul>
</li>
<li><span class="folder"><a>&#8211;</a></span><a href="https://linux.cn/article-8997-1.html#3_4336">插件配置</a><span class="y">32%</span>
<ul class="xl cl">
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_4359">树形目录</a><span class="y">32%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_6227">代码，引号，路径补全</a><span class="y">46%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_6821">语法高亮，检查</a><span class="y">50%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_7581">文件，代码搜索</a><span class="y">56%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_8046">加强版状态栏</a><span class="y">59%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_8484">代码注释</a><span class="y">62%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_9296">git</a><span class="y">68%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_9646">Markdown</a><span class="y">71%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_9960">Emmet</a><span class="y">73%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_10310">html 5</a><span class="y">76%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_10494">css 3</a><span class="y">77%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_11073">JavaScipt</a><span class="y">82%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_12305">React</a><span class="y">91%</span></li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#4_12567">Prettier</a><span class="y">93%</span></li>
</ul>
</li>
<li><span class="folder">&#8211;</span><a href="https://linux.cn/article-8997-1.html#3_13198">总结</a><span class="y">97%</span></li>
</ul>
</div>
</div>
<div id="article_content" class="bm">
<div class="linuxcnad"></div>
<p>Vim 是一个上古神器，本篇文章主要持续总结使用 Vim 的过程中不得不了解的一些指令和注意事项，以及持续分享一个前端工作者不得不安装的一些插件，而关于 Vim 的简介，主题的选择，以及为何使用 vim-plug 来管理插件等内容，有兴趣的同学下来可以自己了解和对比下。</p>
<p><a id="3_463" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h3>安装</h3>
<pre>sudo apt-get install vim  // Ubuntu</pre>
<p>其他平台，可以自行谷歌。</p>
<p><a id="3_573" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h3 id="articleHeader1">新手指南</h3>
<pre>vimtutor  // vim 教程</pre>
<p>上面是史上最简单，最全面的Vim基础教程，至今无人超越。</p>
<p>下面是作者基于上面的归纳：</p>
<p><a id="4_787" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>移动光标</h4>
<pre>hjkl
2w 向前移动两个单词
3e 向前移动到第 3 个单词的末尾
0 移动到行首
$ 当前行的末尾
gg 文件第一行
G 文件最后一行
行号+G 指定行
&lt;ctrl&gt;+o 跳转回之前的位置
&lt;ctrl&gt;+i 返回跳转之前的位置</pre>
<p><a id="4_1088" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>退出</h4>
<pre>&lt;esc&gt; 进入正常模式
:q! 不保存退出
:wq 保存后退出</pre>
<p><a id="4_1190" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>删除</h4>
<pre>x 删除当前字符
dw 删除至当前单词末尾
de 删除至当前单词末尾，包括当前字符
d$ 删除至当前行尾
dd 删除整行
2dd 删除两行</pre>
<p><a id="4_1386" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>修改</h4>
<pre>i 插入文本
A 当前行末尾添加
r 替换当前字符
o 打开新的一行并进入插入模式</pre>
<p><a id="4_1520" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>撤销</h4>
<pre>u 撤销
&lt;ctrl&gt;+r 取消撤销</pre>
<p><a id="4_1587" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>复制粘贴剪切</h4>
<pre>v 进入可视模式
y 复制
p 粘贴
yy 复制当前行
dd 剪切当前行</pre>
<p><a id="4_1709" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>状态</h4>
<pre>&lt;ctrl&gt;+g 显示当前行以及文件信息</pre>
<p><a id="4_1787" class="target-fix ext" target="_blank" rel="external nofollow"></a><a id="4_3623" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>查找</h4>
<pre>/ 正向查找（n：继续查找，N：相反方向继续查找）
? 逆向查找
% 查找配对的 {，[，(
:set ic 忽略大小写
:set noic 取消忽略大小写
:set hls 匹配项高亮显示
:set is 显示部分匹配</pre>
<p><a id="4_2047" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>替换</h4>
<pre>:s/old/new 替换该行第一个匹配串
:s/old/new/g 替换全行的匹配串
:%s/old/new/g 替换整个文件的匹配串</pre>
<p><a id="4_2203" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>折叠</h4>
<pre>zc 折叠
zC 折叠所有嵌套
zo 展开折叠
zO 展开所有折叠嵌套</pre>
<p><a id="4_2311" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>执行外部命令</h4>
<pre>:!shell 执行外部命令</pre>
<p><a id="3_2379" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h3 id="articleHeader13">.vimrc</h3>
<p><code>.vimrc</code> 是 Vim 的配置文件，需要我们自己创建：</p>
<pre>cd Home               // 进入 Home 目录
touch .vimrc          // 配置文件

# Unix
# vim-plug
# Vim
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
# Neovim
curl -fLo ~/.local/share/nvim/site/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim</pre>
<p>其他平台，可以查看 <a class="ext" href="https://github.com/junegunn/vim-plug" target="_blank" rel="external nofollow noopener">vim-plug</a>。</p>
<p><a id="3_3047" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h3>基本配置</h3>
<p><a id="4_3070" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader15">取消备份</h4>
<pre>set nobackup
set noswapfile</pre>
<p><a id="4_3155" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader16">文件编码</h4>
<pre>set encoding=utf-8</pre>
<p><a id="4_3230" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader17">显示行号</h4>
<pre>set number</pre>
<p><a id="4_3297" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader18">取消换行</h4>
<pre>set nowrap</pre>
<p><a id="4_3364" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader19">显示光标当前位置</h4>
<pre>set ruler</pre>
<p><a id="4_3442" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader20">设置缩进</h4>
<pre>set cindent
set tabstop=2
set shiftwidth=2</pre>
<p><a id="4_3543" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader21">突出显示当前行</h4>
<pre>set cursorline</pre>
<p><a id="4_1787" class="target-fix ext" target="_blank" rel="external nofollow"></a><a id="4_3623" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader22">查找</h4>
<pre>set ic
set hls
set is</pre>
<p><a id="4_3697" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader23">左下角显示当前 vim 模式</h4>
<pre>set showmode</pre>
<p><a id="4_2203" class="target-fix ext" target="_blank" rel="external nofollow"></a><a id="4_3786" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader24">代码折叠</h4>
<pre># 启动 vim 时关闭折叠代码
set nofoldenable</pre>
<p><a id="4_3895" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader25">主题</h4>
<pre>syntax enable
set background=dark
colorscheme solarized</pre>
<ul>
<li><a class="ext" href="https://github.com/altercation/vim-colors-solarized" target="_blank" rel="external nofollow noopener">altercation/vim-colors-solarized</a></li>
<li><a class="ext" href="https://github.com/Anthony25/gnome-terminal-colors-solarized" target="_blank" rel="external nofollow noopener">Anthony25/gnome-terminal-colors-solarized</a></li>
</ul>
<p><a id="3_4336" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h3>插件配置</h3>
<p><a id="4_4359" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader27">树形目录</h4>
<pre>Plug 'scrooloose/nerdtree'
Plug 'jistr/vim-nerdtree-tabs'
Plug 'Xuyuanp/nerdtree-git-plugin'

autocmd vimenter * NERDTree
map &lt;C-n&gt; :NERDTreeToggle&lt;CR&gt;
let NERDTreeShowHidden=1
let g:NERDTreeShowIgnoredStatus = 1
let g:nerdtree_tabs_open_on_console_startup=1
let g:NERDTreeIndicatorMapCustom = {
    \ "Modified"  : "✹",
    \ "Staged"    : "✚",
    \ "Untracked" : "✭",
    \ "Renamed"   : "➜",
    \ "Unmerged"  : "═",
    \ "Deleted"   : "&#x2716;",
    \ "Dirty"     : "✗",
    \ "Clean"     : "&#x2714;︎",
    \ 'Ignored'   : '☒',
    \ "Unknown"   : "?"
    \ }

# o 打开关闭文件或目录
# e 以文件管理的方式打开选中的目录
# t 在标签页中打开
# T 在标签页中打开，但光标仍然留在 NERDTree
# r 刷新光标所在的目录
# R 刷新当前根路径
# X 收起所有目录
# p 小写，跳转到光标所在的上一级路径
# P 大写，跳转到当前根路径
# J 到第一个节点
# K 到最后一个节点
# I 显示隐藏文件
# m 显示文件操作菜单
# C 将根路径设置为光标所在的目录
# u 设置上级目录为根路径
# ctrl + w + w 光标自动在左右侧窗口切换
# ctrl + w + r 移动当前窗口的布局位置
# :tabc 关闭当前的 tab
# :tabo   关闭所有其他的 tab
# :tabp   前一个 tab
# :tabn   后一个 tab
# gT      前一个 tab
# gt      后一个 tab</pre>
<ul>
<li><a class="ext" href="https://github.com/scrooloose/nerdtree" target="_blank" rel="external nofollow noopener">scrooloose/nerdtree</a></li>
<li><a class="ext" href="https://github.com/jistr/vim-nerdtree-tabs" target="_blank" rel="external nofollow noopener">vim-nerdtree-tabs</a></li>
<li><a class="ext" href="https://github.com/Xuyuanp/nerdtree-git-plugin" target="_blank" rel="external nofollow noopener">nerdtree-git-plugin</a></li>
</ul>
<p><a id="4_6227" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader28">代码，引号，路径补全</h4>
<pre>Plug 'Valloric/YouCompleteMe'
Plug 'Raimondi/delimitMate'
Plug 'Shougo/deoplete.nvim', { 'do': ':UpdateRemotePlugins' }</pre>
<ul>
<li><a class="ext" href="https://github.com/Valloric/YouCompleteMe" target="_blank" rel="external nofollow noopener">Valloric/YouCompleteMe</a></li>
<li><a class="ext" href="https://github.com/Raimondi/delimitMate" target="_blank" rel="external nofollow noopener">Raimondi/delimitMate</a></li>
<li><a class="ext" href="https://github.com/Shougo/deoplete.nvim" target="_blank" rel="external nofollow noopener">Shougo/deoplete.nvim</a></li>
</ul>
<p><a id="4_6821" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>语法高亮，检查</h4>
<pre>Plug 'sheerun/vim-polyglot'
Plug 'w0rp/ale'

let g:ale_linters = {
\    'javascript': ['eslint'],
\    'css': ['stylelint'],
\}
let g:ale_fixers = {
\    'javascript': ['eslint'],
\    'css': ['stylelint'],
\}
let g:ale_fix_on_save = 1

let g:ale_sign_column_always = 1
let g:ale_sign_error = '●'
let g:ale_sign_warning = '&#x25b6;'

nmap &lt;silent&gt; &lt;C-k&gt; &lt;Plug&gt;(ale_previous_wrap)
nmap &lt;silent&gt; &lt;C-j&gt; &lt;Plug&gt;(ale_next_wrap)</pre>
<ul>
<li><a class="ext" href="https://github.com/w0rp/ale" target="_blank" rel="external nofollow noopener">w0rp/ale</a></li>
<li><a class="ext" href="https://github.com/sheerun/vim-polyglot" target="_blank" rel="external nofollow noopener">sheerun/vim-polyglot</a></li>
</ul>
<p><a id="4_7581" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>文件，代码搜索</h4>
<pre>Plug 'rking/ag.vim'
Plug 'kien/ctrlp.vim'</pre>
<ul>
<li><a class="ext" href="https://github.com/kien/ctrlp.vim" target="_blank" rel="external nofollow noopener">kien/ctrlp.vim</a></li>
<li><a class="ext" href="https://github.com/ggreer/the_silver_searcher" target="_blank" rel="external nofollow noopener">ggreer/the_silver_searcher</a></li>
<li><a class="ext" href="https://github.com/rking/ag.vim" target="_blank" rel="external nofollow noopener">rking/ag.vim</a></li>
</ul>
<p><a id="4_1709" class="target-fix ext" target="_blank" rel="external nofollow"></a><a id="4_8046" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>加强版状态栏</h4>
<pre>Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'
let g:airline_theme='papercolor'</pre>
<ul>
<li><a class="ext" href="https://github.com/vim-airline/vim-airline" target="_blank" rel="external nofollow noopener">vim-airline/vim-airline</a></li>
<li><a class="ext" href="https://github.com/vim-airline/vim-airline-themes" target="_blank" rel="external nofollow noopener">vim-airline/vim-airline-themes</a></li>
</ul>
<p><a id="4_8484" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>代码注释</h4>
<pre>Plug 'scrooloose/nerdcommenter'

# &lt;leader&gt;cc // 注释
# &lt;leader&gt;cm 只用一组符号注释
# &lt;leader&gt;cA 在行尾添加注释
# &lt;leader&gt;c$ /* 注释 */
# &lt;leader&gt;cs /* 块注释 */
# &lt;leader&gt;cy 注释并复制
# &lt;leader&gt;c&lt;space&gt; 注释/取消注释
# &lt;leader&gt;ca 切换　// 和 /* */
# &lt;leader&gt;cu 取消注释

let g:NERDSpaceDelims = 1
let g:NERDDefaultAlign = 'left'
let g:NERDCustomDelimiters = {
            \ 'javascript': { 'left': '//', 'leftAlt': '/**', 'rightAlt': '*/' },
            \ 'less': { 'left': '/**', 'right': '*/' }
        \ }</pre>
<ul>
<li><a class="ext" href="https://github.com/scrooloose/nerdcommenter" target="_blank" rel="external nofollow noopener">scrooloose/nerdcommenter</a></li>
</ul>
<p><a id="4_9296" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>git</h4>
<pre>Plug 'airblade/vim-gitgutter'
Plug 'tpope/vim-fugitive'</pre>
<ul>
<li><a class="ext" href="https://github.com/airblade/vim-gitgutter" target="_blank" rel="external nofollow noopener">airblade/vim-gitgutter</a></li>
<li><a class="ext" href="https://github.com/tpope/vim-fugitive" target="_blank" rel="external nofollow noopener">tpope/vim-fugitive</a></li>
</ul>
<p><a id="4_9646" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>Markdown</h4>
<pre>Plug 'suan/vim-instant-markdown'

let g:instant_markdown_slow = 1
let g:instant_markdown_autostart = 0
# :InstantMarkdownPreview</pre>
<ul>
<li><a class="ext" href="https://github.com/suan/vim-instant-markdown" target="_blank" rel="external nofollow noopener">suan/vim-instant-markdown</a></li>
</ul>
<p><a id="4_9960" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>Emmet</h4>
<pre>Plug 'mattn/emmet-vim'

let g:user_emmet_leader_key='&lt;Tab&gt;'
let g:user_emmet_settings = {
         \ 'javascript.jsx' : {
            \ 'extends' : 'jsx',
         \ },
      \ }</pre>
<ul>
<li><a class="ext" href="https://github.com/mattn/emmet-vim" target="_blank" rel="external nofollow noopener">mattn/emmet-vim</a></li>
</ul>
<p><a id="4_10310" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>html 5</h4>
<pre>Plug'othree/html5.vim'</pre>
<ul>
<li><a class="ext" href="https://github.com/othree/html5.vim" target="_blank" rel="external nofollow noopener">othree/html5.vim</a></li>
</ul>
<p><a id="4_10494" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4>css 3</h4>
<p class="article_img"><img decoding="async" src="https://dn-linuxcn.qbox.me/data/attachment/album/201710/24/184022uws9jsywf9wdd149.png" data-src="/img/bVWLbE?w=684&amp;h=451" /></p>
<pre>Plug 'hail2u/vim-css3-syntax'
Plug 'ap/vim-css-color'

augroup VimCSS3Syntax
  autocmd!

  autocmd FileType css setlocal iskeyword+=-
augroup END</pre>
<ul>
<li><a class="ext" href="https://github.com/hail2u/vim-css3-syntax" target="_blank" rel="external nofollow noopener">hail2u/vim-css3-syntax</a></li>
<li><a class="ext" href="https://github.com/ap/vim-css-color" target="_blank" rel="external nofollow noopener">ap/vim-css-color</a></li>
</ul>
<p><a id="4_11073" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader38">JavaScipt</h4>
<ol class="linenums">
<li class="L0"><code><span class="typ">Plug</span> <span class="str">'pangloss/vim-javascript'</span></code></li>
<li class="L1"><code></code></li>
<li class="L2"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_plugin_jsdoc </span><span class="pun">=</span> <span class="lit">1</span></code></li>
<li class="L3"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_plugin_ngdoc </span><span class="pun">=</span> <span class="lit">1</span></code></li>
<li class="L4"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_plugin_flow </span><span class="pun">=</span> <span class="lit">1</span></code></li>
<li class="L5"><code><span class="kwd">set</span><span class="pln"> foldmethod</span><span class="pun">=</span><span class="pln">syntax</span></code></li>
<li class="L6"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_conceal_function             </span><span class="pun">=</span> <span class="str">"ƒ"</span></code></li>
<li class="L7"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_conceal_null                 </span><span class="pun">=</span> <span class="str">"ø"</span></code></li>
<li class="L8"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_conceal_this                 </span><span class="pun">=</span> <span class="str">"@"</span></code></li>
<li class="L9"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_conceal_return               </span><span class="pun">=</span> <span class="str">"⇚"</span></code></li>
<li class="L0"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_conceal_undefined            </span><span class="pun">=</span> <span class="str">"¿"</span></code></li>
<li class="L1"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_conceal_NaN                  </span><span class="pun">=</span> <span class="str">"ℕ"</span></code></li>
<li class="L2"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_conceal_prototype            </span><span class="pun">=</span> <span class="str">"¶"</span></code></li>
<li class="L3"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_conceal_static               </span><span class="pun">=</span> <span class="str">"•"</span></code></li>
<li class="L4"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_conceal_super                </span><span class="pun">=</span> <span class="str">"Ω"</span></code></li>
<li class="L5"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_conceal_arrow_function       </span><span class="pun">=</span> <span class="str">"⇒"</span></code></li>
<li class="L6"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_conceal_noarg_arrow_function </span><span class="pun">=</span> <span class="str">" "</span></code></li>
<li class="L7"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">javascript_conceal_underscore_arrow_function </span><span class="pun">=</span> <span class="str">" "</span></code></li>
<li class="L8"><code><span class="kwd">set</span><span class="pln"> conceallevel</span><span class="pun">=</span><span class="lit">1</span></code></li>
</ol>
<ul>
<li><a class="ext" href="https://github.com/pangloss/vim-javascript" target="_blank" rel="external nofollow noopener">pangloss/vim-javascript</a></li>
</ul>
<p>（注：上述脚本中存在特殊字符，有的情况下显示不正确，请直接用上述链接的内容。）</p>
<p><a id="4_12305" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader39">React</h4>
<ol class="linenums">
<li class="L0"><code><span class="typ">Plug</span> <span class="str">'mxw/vim-jsx'</span></code></li>
<li class="L1"><code></code></li>
<li class="L2"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">jsx_ext_required </span><span class="pun">=</span> <span class="lit">0</span></code></li>
</ol>
<ul>
<li><a class="ext" href="https://github.com/mxw/vim-jsx" target="_blank" rel="external nofollow noopener">mxw/vim-jsx</a></li>
</ul>
<p><a id="4_12567" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h4 id="articleHeader40">Prettier</h4>
<ol class="linenums">
<li class="L0"><code><span class="typ">Plug</span> <span class="str">'prettier/vim-prettier'</span><span class="pun">,</span> <span class="pun">{</span></code></li>
<li class="L1"><code><span class="pln">  \ </span><span class="str">'do'</span><span class="pun">:</span> <span class="str">'yarn install'</span><span class="pun">,</span></code></li>
<li class="L2"><code><span class="pln">  \ </span><span class="str">'for'</span><span class="pun">:</span> <span class="pun">[</span><span class="str">'javascript'</span><span class="pun">,</span> <span class="str">'typescript'</span><span class="pun">,</span> <span class="str">'css'</span><span class="pun">,</span> <span class="str">'less'</span><span class="pun">,</span> <span class="str">'scss'</span><span class="pun">,</span> <span class="str">'json'</span><span class="pun">,</span> <span class="str">'graphql'</span><span class="pun">]</span> <span class="pun">}</span></code></li>
<li class="L3"><code></code></li>
<li class="L4"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">prettier</span><span class="com">#</span><span class="pln">config</span><span class="com">#</span><span class="pln">bracket_spacing </span><span class="pun">=</span> <span class="str">'true'</span></code></li>
<li class="L5"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">prettier</span><span class="com">#</span><span class="pln">config</span><span class="com">#</span><span class="pln">jsx_bracket_same_line </span><span class="pun">=</span> <span class="str">'false'</span></code></li>
<li class="L6"><code><span class="pln">let g</span><span class="pun">:</span><span class="pln">prettier</span><span class="com">#</span><span class="pln">autoformat </span><span class="pun">=</span> <span class="lit">0</span></code></li>
<li class="L7"><code><span class="pln">autocmd </span><span class="typ">BufWritePre</span> <span class="pun">*.</span><span class="pln">js</span><span class="pun">,*.</span><span class="pln">jsx</span><span class="pun">,*.</span><span class="pln">mjs</span><span class="pun">,*.</span><span class="pln">ts</span><span class="pun">,*.</span><span class="pln">tsx</span><span class="pun">,*.</span><span class="pln">css</span><span class="pun">,*.</span><span class="kwd">less</span><span class="pun">,*.</span><span class="pln">scss</span><span class="pun">,*.</span><span class="pln">json</span><span class="pun">,*.</span><span class="pln">graphql </span><span class="typ">PrettierAsync</span></code></li>
<li class="L8"><code></code></li>
<li class="L9"><code><span class="com">#</span> <span class="pun">:</span><span class="typ">Prettier</span></code></li>
</ol>
<ul>
<li><a class="ext" href="https://github.com/prettier/vim-prettier" target="_blank" rel="external nofollow noopener">prettier/vim-prettier</a></li>
</ul>
<p><a id="3_13198" class="target-fix ext" target="_blank" rel="external nofollow"></a></p>
<h3 id="articleHeader41">总结</h3>
<p>最后，呈上参考配置 <a class="ext" href="https://github.com/FengShangWuQi/to-vim/blob/master/.vimrc" target="_blank" rel="external nofollow noopener">.vimrc</a>，如果关于 vim 有更好的 idea，欢迎在评论中交流。</p>
</div>
</div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>linux重定向及nohup不输出的方法</title>
		<link>https://www.bhzhu203.com/2017/08/25/linux%e9%87%8d%e5%ae%9a%e5%90%91%e5%8f%8anohup%e4%b8%8d%e8%be%93%e5%87%ba%e7%9a%84%e6%96%b9%e6%b3%95/</link>
		
		<dc:creator><![CDATA[bhzhu203]]></dc:creator>
		<pubDate>Fri, 25 Aug 2017 11:44:17 +0000</pubDate>
				<category><![CDATA[linux知识]]></category>
		<category><![CDATA[输出]]></category>
		<category><![CDATA[重定向]]></category>
		<category><![CDATA[错误信息]]></category>
		<guid isPermaLink="false">http://www.bhzhu203.com/?p=439</guid>

					<description><![CDATA[from http://hi.baidu.com/zhaolegend/blog [&#8230;]]]></description>
										<content:encoded><![CDATA[<div id="article_content" class="article_content tracking-ad" data-mod="popu_307" data-dsm="post">
<p>from <a href="http://hi.baidu.com/zhaolegend/blog/item/245ad226e860bdfed7cae2ed.html" target="_blank">http://hi.baidu.com/zhaolegend/blog/item/245ad226e860bdfed7cae2ed.html</a></p>
<p>先说一下linux重定向：</p>
<p>0、1和2分别表示标准输入、标准输出和标准错误信息输出，可以用来指定需要重定向的标准输入或输出。<br />
在一般使用时，默认的是标准输出，既1.当我们需要特殊用途时，可以使用其他标号。例如，将某个程序的错误信息输出到log文件中：./program 2&gt;log。这样标准输出还是在屏幕上，但是错误信息会输出到log文件中。<br />
另外，也可以实现0，1，2之间的重定向。2&gt;&amp;1：将错误信息重定向到标准输出。<br />
Linux下还有一个特殊的文件/dev/null，它就像一个无底洞，所有重定向到它的信息都会消失得无影无踪。这一点非常有用，当我们不需要回显程序的所有信息时，就可以将输出重定向到/dev/null。<br />
如果想要正常输出和错误信息都不显示，则要把标准输出和标准错误都重定向到/dev/null， 例如：</p>
<p># ls 1&gt;/dev/null 2&gt;/dev/null</p>
<p>还有一种做法是将错误重定向到标准输出，然后再重定向到 /dev/null，例如：</p>
<p># ls &gt;/dev/null 2&gt;&amp;1</p>
<p>注意：此处的顺序不能更改，否则达不到想要的效果，此时先将标准输出重定向到 /dev/null，然后将标准错误重定向到标准输出，由于标准输出已经重定向到了/dev/null，因此标准错误也会重定向到/dev/null，于是一切静悄悄:-)</p>
<p>由于使用nohup时，会自动将输出写入nohup.out文件中，如果文件很大的话，nohup.out就会不停的增大，这是我们不希望看到的，因此，可以利用/dev/null来解决这个问题。</p>
<p>nohup ./program &gt;/dev/null 2&gt;log &amp;</p>
<p>如果错误信息也不想要的话：</p>
<p>nohup ./program &gt;/dev/null 2&gt;&amp;1 &amp;</p>
</div>
<div class="bdsharebuttonbox tracking-ad bdshare-button-style0-16" data-mod="popu_172" data-bd-bind="1503661361730"></div>
<div class="bdsharebuttonbox tracking-ad bdshare-button-style0-16" data-mod="popu_172" data-bd-bind="1503661361730"></div>
<div class="bdsharebuttonbox tracking-ad bdshare-button-style0-16" data-mod="popu_172" data-bd-bind="1503661361730">转载：http://blog.csdn.net/geekster/article/details/6657620</div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ss：查看网络连接的另一种方法</title>
		<link>https://www.bhzhu203.com/2017/08/10/ss%ef%bc%9a%e6%9f%a5%e7%9c%8b%e7%bd%91%e7%bb%9c%e8%bf%9e%e6%8e%a5%e7%9a%84%e5%8f%a6%e4%b8%80%e7%a7%8d%e6%96%b9%e6%b3%95/</link>
		
		<dc:creator><![CDATA[bhzhu203]]></dc:creator>
		<pubDate>Thu, 10 Aug 2017 12:47:55 +0000</pubDate>
				<category><![CDATA[linux知识]]></category>
		<category><![CDATA[netstat]]></category>
		<category><![CDATA[port]]></category>
		<category><![CDATA[ss]]></category>
		<guid isPermaLink="false">http://www.bhzhu203.com/?p=437</guid>

					<description><![CDATA[在之前的文章中，我提到过 ss，它是 iproute2 包附带的另一个工具，允许 [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>在之前的文章中，我提到过 <code>ss</code>，它是 iproute2 包附带的另一个工具，允许你查询 socket 的有关统计信息。可以完成 <code>netstat</code> 同样的任务，但是，<code>ss</code> 稍微快一点而且命令更简短。</p>
<p>直接输入 <code>ss</code>，默认会显示与 <code>netstat</code> 同样的内容，并且输入类似的参数可以获取你想要的类似输出。例如：</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">ss</span> <span class="pun">-</span><span class="pln">t</span></code></li>
<li class="L1"><code><span class="typ">State</span><span class="pln">       </span><span class="typ">Recv</span><span class="pun">-</span><span class="pln">Q </span><span class="typ">Send</span><span class="pun">-</span><span class="pln">Q       </span><span class="typ">Local</span> <span class="typ">Address</span><span class="pun">:</span><span class="typ">Port</span><span class="pln">                        </span><span class="typ">Peer</span> <span class="typ">Address</span><span class="pun">:</span><span class="typ">Port</span></code></li>
<li class="L2"><code><span class="pln">ESTAB       </span><span class="lit">0</span><span class="pln">      </span><span class="lit">0</span><span class="pln">                </span><span class="lit">127.0</span><span class="pun">.</span><span class="lit">0.1</span><span class="pun">:</span><span class="pln">postgresql                     </span><span class="lit">127.0</span><span class="pun">.</span><span class="lit">0.1</span><span class="pun">:</span><span class="lit">48154</span></code></li>
<li class="L3"><code><span class="pln">ESTAB       </span><span class="lit">0</span><span class="pln">      </span><span class="lit">0</span><span class="pln">            </span><span class="lit">192.168</span><span class="pun">.</span><span class="lit">0.136</span><span class="pun">:</span><span class="lit">35296</span><span class="pln">                      </span><span class="lit">192.168</span><span class="pun">.</span><span class="lit">0.120</span><span class="pun">:</span><span class="lit">8009</span></code></li>
<li class="L4"><code><span class="pln">ESTAB       </span><span class="lit">0</span><span class="pln">      </span><span class="lit">0</span><span class="pln">            </span><span class="lit">192.168</span><span class="pun">.</span><span class="lit">0.136</span><span class="pun">:</span><span class="lit">47574</span><span class="pln">                     </span><span class="lit">173.194</span><span class="pun">.</span><span class="lit">74.189</span><span class="pun">:</span><span class="pln">https</span></code></li>
<li class="L5"><code><span class="pun">[…]</span></code></li>
</ol>
<p><code>ss -t</code> 只显示 TCP 连接。<code>ss -u</code> 用于显示 UDP 连接，<code>-l</code> 参数只会显示监听的端口，而且可以进一步过滤到任何想要的信息。</p>
<p>我并没有测试所有可用参数，但是你甚至可以使用 <code>-K</code> 强制关闭 socket。</p>
<p><code>ss</code> 真正耀眼的地方是其内置的过滤能力。让我们列出所有端口为 22（ssh）的连接：</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">ss</span><span class="pln"> state all sport </span><span class="pun">=</span> <span class="pun">:</span><span class="kwd">ssh</span></code></li>
<li class="L1"><code><span class="typ">Netid</span> <span class="typ">State</span><span class="pln">      </span><span class="typ">Recv</span><span class="pun">-</span><span class="pln">Q </span><span class="typ">Send</span><span class="pun">-</span><span class="pln">Q     </span><span class="typ">Local</span> <span class="typ">Address</span><span class="pun">:</span><span class="typ">Port</span><span class="pln">                      </span><span class="typ">Peer</span> <span class="typ">Address</span><span class="pun">:</span><span class="typ">Port</span></code></li>
<li class="L2"><code><span class="pln">tcp   LISTEN     </span><span class="lit">0</span><span class="pln">      </span><span class="lit">128</span><span class="pln">                    </span><span class="pun">*:</span><span class="kwd">ssh</span><span class="pln">                                  </span><span class="pun">*:*</span></code></li>
<li class="L3"><code><span class="pln">tcp   ESTAB      </span><span class="lit">0</span><span class="pln">      </span><span class="lit">0</span><span class="pln">          </span><span class="lit">192.168</span><span class="pun">.</span><span class="lit">0.136</span><span class="pun">:</span><span class="kwd">ssh</span><span class="pln">                      </span><span class="lit">192.168</span><span class="pun">.</span><span class="lit">0.102</span><span class="pun">:</span><span class="lit">46540</span></code></li>
<li class="L4"><code><span class="pln">tcp   LISTEN     </span><span class="lit">0</span><span class="pln">      </span><span class="lit">128</span><span class="pln">                   </span><span class="pun">:::</span><span class="kwd">ssh</span><span class="pln">                                 </span><span class="pun">:::*</span></code></li>
</ol>
<p>如果只想看已建立的 socket（排除了 <em>listening</em> 和 <em>closed</em> ）：</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">ss</span><span class="pln"> state connected sport </span><span class="pun">=</span> <span class="pun">:</span><span class="kwd">ssh</span></code></li>
<li class="L1"><code><span class="typ">Netid</span> <span class="typ">State</span><span class="pln">      </span><span class="typ">Recv</span><span class="pun">-</span><span class="pln">Q </span><span class="typ">Send</span><span class="pun">-</span><span class="pln">Q     </span><span class="typ">Local</span> <span class="typ">Address</span><span class="pun">:</span><span class="typ">Port</span><span class="pln">                      </span><span class="typ">Peer</span> <span class="typ">Address</span><span class="pun">:</span><span class="typ">Port</span></code></li>
<li class="L2"><code><span class="pln">tcp   ESTAB      </span><span class="lit">0</span><span class="pln">      </span><span class="lit">0</span><span class="pln">          </span><span class="lit">192.168</span><span class="pun">.</span><span class="lit">0.136</span><span class="pun">:</span><span class="kwd">ssh</span><span class="pln">                      </span><span class="lit">192.168</span><span class="pun">.</span><span class="lit">0.102</span><span class="pun">:</span><span class="lit">46540</span></code></li>
</ol>
<p>类似的，可以列出指定的 host 或者 ip 段。例如，列出到达 74.125.0.0/16 子网的连接，这个子网属于 Google：</p>
<ol class="linenums">
<li class="L0"><code><span class="pln">$ </span><span class="kwd">ss</span><span class="pln"> state all dst </span><span class="lit">74.125</span><span class="pun">.</span><span class="lit">0.0</span><span class="pun">/</span><span class="lit">16</span></code></li>
<li class="L1"><code><span class="typ">Netid</span> <span class="typ">State</span><span class="pln">      </span><span class="typ">Recv</span><span class="pun">-</span><span class="pln">Q </span><span class="typ">Send</span><span class="pun">-</span><span class="pln">Q     </span><span class="typ">Local</span> <span class="typ">Address</span><span class="pun">:</span><span class="typ">Port</span><span class="pln">                      </span><span class="typ">Peer</span> <span class="typ">Address</span><span class="pun">:</span><span class="typ">Port</span></code></li>
<li class="L2"><code><span class="pln">tcp   ESTAB      </span><span class="lit">0</span><span class="pln">      </span><span class="lit">0</span><span class="pln">          </span><span class="lit">192.168</span><span class="pun">.</span><span class="lit">0.136</span><span class="pun">:</span><span class="lit">33616</span><span class="pln">                   </span><span class="lit">74.125</span><span class="pun">.</span><span class="lit">142.189</span><span class="pun">:</span><span class="pln">https</span></code></li>
<li class="L3"><code><span class="pln">tcp   ESTAB      </span><span class="lit">0</span><span class="pln">      </span><span class="lit">0</span><span class="pln">          </span><span class="lit">192.168</span><span class="pun">.</span><span class="lit">0.136</span><span class="pun">:</span><span class="lit">42034</span><span class="pln">                    </span><span class="lit">74.125</span><span class="pun">.</span><span class="lit">70.189</span><span class="pun">:</span><span class="pln">https</span></code></li>
<li class="L4"><code><span class="pln">tcp   ESTAB      </span><span class="lit">0</span><span class="pln">      </span><span class="lit">0</span><span class="pln">          </span><span class="lit">192.168</span><span class="pun">.</span><span class="lit">0.136</span><span class="pun">:</span><span class="lit">57408</span><span class="pln">                   </span><span class="lit">74.125</span><span class="pun">.</span><span class="lit">202.189</span><span class="pun">:</span><span class="pln">https</span></code></li>
</ol>
<p><code>ss</code>与 iptables 的语法非常相同，如果已经熟悉了其语法，<code>ss</code> 非常容易上手。也可以安装 iproute2-doc 包， 通过 <code>/usr/share/doc/iproute2-doc/ss.html</code> 获得完整文档。</p>
<p>还不快试试! 你就可以知道它有多棒。无论如何，让我输入的字符越少我越高兴。</p>
<hr />
<p>via: <a class="ext" href="https://insights.ubuntu.com/2017/07/25/ss-another-way-to-get-socket-statistics/" target="_blank" rel="external nofollow">https://insights.ubuntu.com/2017/07/25/ss-another-way-to-get-socket-statistics/</a></p>
<p>作者：<a class="ext" href="https://insights.ubuntu.com/author/mathieu-trudel-lapierre/" target="_blank" rel="external nofollow">Mathieu Trudel-Lapierre</a> 译者：<a class="ext" href="https://vicyu.com" target="_blank" rel="external nofollow">VicYu</a> 校对：<a class="ext" href="https://github.com/wxy" target="_blank" rel="external nofollow">wxy</a></p>
<p>本文由 <a class="ext" href="https://github.com/LCTT/TranslateProject" target="_blank" rel="external nofollow">LCTT</a> 原创编译，<a href="https://linux.cn/article-8727-1.html?utm_source=index&amp;utm_medium=more">Linux中国</a> 荣誉推出</p>
<p>&nbsp;</p>
<p>转自：https://linux.cn/article-8727-1.html?utm_source=index&amp;utm_medium=more</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
