Bash 脚本捕获输出到终端

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11800614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:56:01  来源:igfitidea点击:

Bash script capturing output to terminal

stringbashshell

提问by JDS

I want to capture into my bash script (in a variable) the output of some command that prints its output to terminal. I have tried the following:

我想将某些命令的输出捕获到我的 bash 脚本中(在一个变量中),该命令将其输出打印到终端。我尝试了以下方法:

TEST_OUT=`the_command ARG1`   #Nope

#Putting the line "the_command ARG1" into a separate script, testing2.sh,

TEST_OUT=$(./testing2.sh)   #Nope

testing2.sh
TEST_OUT=$?  #Nope

I am 100% sure that when I run...

我100%确定当我跑步时...

> the_command ARG1

...in a terminal, it prints to the terminal exactly the information I want to capture.

...在终端中,它会准确地向终端打印我想要捕获的信息。

Thank you for any help!

感谢您的任何帮助!

回答by Shawn Chin

If the output is being sent to stderr, you'll need to redirect that to stdout before it can be capture in your var. Try:

如果输出被发送到 stderr,则需要将其重定向到 stdout,然后才能在 var 中捕获它。尝试:

TEST_OUT=$(the_command ARG1 2>&1)