首页 文章

如何将输出从bash脚本重定向到stderr

提问于
浏览
1

我写了一个bash脚本 . 它有一些echo语句 . 它调用了一些第三方工具 . 我想将所有转到stdout的内容(从我的echo语句和所有工具输出)重定向到stderr . 我怎么做?

3 回答

  • 1

    您需要将命令的stdout重定向到stderr .

    your_command.sh 1>&2

    如果要在脚本中执行此操作,可以将整个脚本包装到一个函数中,并将其输出重定向到stderr:

    main() {
       echo hello
       echo world
       some_script.sh
    }
    
    main 1>&2
    
  • 4
    exec >&2
    

    将它放在脚本的顶部,将所有将来的输出重定向到stderr .

    $ help exec
    exec: exec [-cl] [-a name] [command [arguments ...]] [redirection ...]
        Replace the shell with the given command.
    
        Execute COMMAND, replacing this shell with the specified program.
        ARGUMENTS become the arguments to COMMAND.  If COMMAND is not specified,
        any redirections take effect in the current shell.
    
  • 3

    对我有用的解决方案是将脚本文本包含在()中并将stdout重定向到stderr,如下所示:
    ( echo 1 echo 2 tool1 ) 1>&2

相关问题