繁体   English   中英

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

[英]How do I redirect the output from a bash script to stderr

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

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

your_command.sh 1>&2

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

main() {
   echo hello
   echo world
   some_script.sh
}

main 1>&2
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.

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM