【问题标题】:Why Using "< /dev/null" with a program like "bzip2"?为什么将“< /dev/null”与“bzip2”之类的程序一起使用?
【发布时间】:2020-01-15 18:01:38
【问题描述】:

bzip2 --version 2&gt;&amp;1 &lt; /dev/null | head -n1 | cut -d" " -f1,7-

我在 LFS 书中看到了这段代码,那里的&lt; /dev/null 的目的是什么? 我知道&lt; /dev/null 用于防止程序通过发送零来等待输入,但这里有必要吗?

【问题讨论】:

    标签: linux 64-bit bzip2 linux-from-scratch


    【解决方案1】:

    是的,这是必要的。

    从当前版本 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 进行管道传输时,它只会挂起,等待标准输入上的数据。 &lt; /dev/null 通过提供一个可以压缩的零长度文件来防止这种情况。 (这确实在输出的末尾添加了一些二进制垃圾,但它被head 过滤掉了,所以没关系)。

    Debian(及其下游如 Ubuntu)将 patch this out,使 &lt; /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 并没有受益于任何发行版的特定补丁。

    【讨论】:

      【解决方案2】:

      短语&lt; /dev/null 是bzip2 的stdin。很可能,过去需要只是一种好的做法来说明每个标准流,并且作者的年龄足够大,仍然可以这样做。三个标准流是stdinstdoutstderr,都在这里使用。

      我个人会选择bzip2 --version 2&gt;&amp;1 | head -n1 | cut -d" " -f1,7-,因为bzip2 --version 不会因为错过stdin 而失败。

      它可能只是 LFS 所需要的。 Ubuntu 不需要它。

      【讨论】:

        猜你喜欢
        • 2011-08-13
        • 2017-01-25
        • 2012-07-14
        • 2018-07-05
        • 2018-02-06
        • 1970-01-01
        • 1970-01-01
        • 2018-10-14
        • 1970-01-01
        相关资源
        最近更新 更多