【问题标题】:How to redirect standard error to a file如何将标准错误重定向到文件
【发布时间】:2017-09-26 17:14:21
【问题描述】:

在 linux 中,如果我想将标准错误重定向到文件,我可以这样做:

$ls -l /bin/usr 2> ls-error.txt

但是当我尝试时:

$foo=
$echo ${foo:?"parameter is empty"} 2> ls-error.txt

终端的结果是:

bash: foo: parameter is empty

这行不通! 有人可以解释为什么吗? 我以为${parameter:?word} 会将 word 的值发送到标准错误。

【问题讨论】:

    标签: linux bash io-redirection


    【解决方案1】:

    如果您想同时重定向标准和错误输出,并且在执行命令时仍然收到这些消息,您可以使用 tee 命令:

    $echo ${foo:?"parameter is empty"} |& tee -a ls-error.txt
    

    【讨论】:

      【解决方案2】:

      echo ${foo:?"parameter is empty"} 2>ls-error.txt重定向echostderr,但是错误信息是shell在展开时产生的 ${foo:?"parameter is empty"}.

      您可以通过重定向块(或子shell)来获得所需的结果,以便将shell的stderr包含在重定向中:

      { echo "${foo:?"parameter is empty"}"; } 2>ls-error.txt
      

      【讨论】:

        【解决方案3】:

        试试这个命令: ($echo ${foo:?"参数为空"}) 2> ls-error.txt

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-05
          • 2022-01-05
          • 2010-10-29
          • 1970-01-01
          • 1970-01-01
          • 2020-02-10
          • 2021-03-30
          • 1970-01-01
          相关资源
          最近更新 更多