将标准错误和标准输出从 bash 脚本变量回显到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21042455/
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 09:12:46  来源:igfitidea点击:

echo stderr and stdout to file from bash script variable

linuxbashstdoutstderr

提问by 123onetwothree

I have a bash script and inside this bash script I have a JAVARESULT variable like this :

我有一个 bash 脚本,在这个 bash 脚本中,我有一个像这样的 JAVARESULT 变量:

JAVARESULT=`java -cp ... parser_file $file $someextravar`

and what I want is to catch in a log file the stderr and stdout of this result variable.

我想要的是在日志文件中捕获此结果变量的 stderr 和 stdout。

echo "$JAVARESULT" > $LOG_FILE

but i get only the stdout not the stderr. I tried with :

但我只得到标准输出而不是标准错误。我试过:

echo "$JAVARESULT" &> $LOG_FILE

but I don't get the java errors in the log file .

但我没有在日志文件中收到 java 错误。

回答by rul

In every Unix based system every process have at least three file descriptors open. As you know, file descriptors are identified by numbers. This three standard file descriptors are:

在每个基于 Unix 的系统中,每个进程至少打开三个文件描述符。如您所知,文件描述符由数字标识。这三个标准文件描述符是:

  • 0 for stdin
  • 1 for stdout
  • 2 for stderr
  • 0 为 stdin
  • 1 为 stdout
  • 2 为 stderr

What you want to do is redirect stderrto stdout, and then redirect stdoutto a file. So, in your JAVARESULTvariable you'll just have to append:

您想要做的是重定向stderrstdout,然后重定向stdout到一个文件。所以,在你的JAVARESULT变量中,你只需要附加:

2>&1

What you're saying here is: redirect stderr(file descriptor 2) to stdout(file descriptor 1).

你在这里说的是:重定向stderr(文件描述符2)到stdout(文件描述符1)。

回答by Seb

Try this:

尝试这个:

echo "$JAVARESULT" > $LOG_FILE 2>&1

回声“$JAVARESULT”> $LOG_FILE 2>&1