【发布时间】:2020-01-15 18:01:38
【问题描述】:
bzip2 --version 2>&1 < /dev/null | head -n1 | cut -d" " -f1,7-
我在 LFS 书中看到了这段代码,那里的< /dev/null 的目的是什么?
我知道< /dev/null 用于防止程序通过发送零来等待输入,但这里有必要吗?
【问题讨论】:
标签: linux 64-bit bzip2 linux-from-scratch
bzip2 --version 2>&1 < /dev/null | head -n1 | cut -d" " -f1,7-
我在 LFS 书中看到了这段代码,那里的< /dev/null 的目的是什么?
我知道< /dev/null 用于防止程序通过发送零来等待输入,但这里有必要吗?
【问题讨论】:
标签: linux 64-bit bzip2 linux-from-scratch
是的,这是必要的。
从当前版本 1.0.8 开始,bzip2 --version 将打印版本信息,但它还将继续压缩stdin:
$ ./bzip2 --version
bzip2, a block-sorting file compressor. Version 1.0.8, 13-Jul-2019.
Copyright (C) 1996-2019 by Julian Seward.
This program is free software; [...]
bzip2: I won't write compressed data to a terminal.
bzip2: For help, type: `bzip2 --help'.
当另外通过head 进行管道传输时,它只会挂起,等待标准输入上的数据。 < /dev/null 通过提供一个可以压缩的零长度文件来防止这种情况。 (这确实在输出的末尾添加了一些二进制垃圾,但它被head 过滤掉了,所以没关系)。
Debian(及其下游如 Ubuntu)将 patch this out,使 < /dev/null 不必要:
@@ -1916,8 +1918,8 @@ IntNative main ( IntNative argc, Char *a
if (ISFLAG("--keep")) keepInputFiles = True; else
if (ISFLAG("--small")) smallMode = True; else
if (ISFLAG("--quiet")) noisy = False; else
- if (ISFLAG("--version")) license(); else
- if (ISFLAG("--license")) license(); else
+ if (ISFLAG("--version")) { license(); exit ( 0 ); } else
+ if (ISFLAG("--license")) { license(); exit ( 0 ); } else
if (ISFLAG("--exponential")) workFactor = 1; else
if (ISFLAG("--repetitive-best")) redundant(aa->name); else
if (ISFLAG("--repetitive-fast")) redundant(aa->name); else
但显然,Linux From Scratch 并没有受益于任何发行版的特定补丁。
【讨论】:
短语< /dev/null 是bzip2 的stdin。很可能,过去需要或只是一种好的做法来说明每个标准流,并且作者的年龄足够大,仍然可以这样做。三个标准流是stdin、stdout 和stderr,都在这里使用。
我个人会选择bzip2 --version 2>&1 | head -n1 | cut -d" " -f1,7-,因为bzip2 --version 不会因为错过stdin 而失败。
它可能只是 LFS 所需要的。 Ubuntu 不需要它。
【讨论】: