首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >批处理-如何从批处理脚本本身重定向stderr和stdout?

批处理-如何从批处理脚本本身重定向stderr和stdout?
EN

Stack Overflow用户
提问于 2012-04-20 10:52:25
回答 2查看 6.4K关注 0票数 3

在Unix shell脚本中,可以从内部脚本本身重定向stderr和stdout,如下所示:

代码语言:javascript
复制
#!/bin/ksh
# script_name: test.sh
export AUTO_LOGFILE=`basename $0 .sh`.log
# stdout and stderr Redirection. This will save the old stdout on FD 3, and the old stderr on FD 4.
exec 3>&0 4>&1 >>$AUTO_LOGFILE 2>&1
echo "Hello World"
# The above echo will be printed to test.log

实际上,test.sh可以简单地执行为:

代码语言:javascript
复制
test.sh

而不是:

代码语言:javascript
复制
test.sh >> test.log 2>&1    

我正在试着在批处理脚本中做类似的事情。我的批次代码如下:

代码语言:javascript
复制
@echo off & setlocal enableextensions enabledelayedexpansion
REM script_name=test.bat
set AUTO_LOGFILE=%~n0.log
REM How to do the stdout and stderr redirection from within the script itself here?

如何从批处理脚本本身重定向stderr和stdout?我更感兴趣的是将这个unix shell脚本语句转换成等价的批处理代码:

代码语言:javascript
复制
exec 3>&0 4>&1 >>$AUTO_LOGFILE 2>&1
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-22 01:03:41

下面的test.bat批处理文件在功能上等同于您的Unix脚本,即它将所有标准输出发送到日志文件,并将错误输出发送到屏幕:

代码语言:javascript
复制
@echo off
if defined reEntry goto reEntry
set reEntry=TRUE

set AUTO_LOGFILE=%~N0.log
rem stdout Redirection. Leave stderr as is.

"%~F0" %* >>%AUTO_LOGFILE%

:reEntry
set reEntry=
echo "Hello World"
rem The above echo will be printed to test.log
rem and error messages will be printed to the screen:
verify badparam

附件:

我以为OP希望将stdout与stderr分开,以便在屏幕上看到错误消息,但也许我误解了他。要将stdout和stderr发送到该文件,请使用dbenham注释中提到的以下行:

代码语言:javascript
复制
"%~F0" %* >>%AUTO_LOGFILE% 2>&1

或者用上面的评论中已经建议的更简单的方式:

代码语言:javascript
复制
@echo off
set AUTO_LOGFILE=%~N0.log
rem stdout and stderr Redirection.

call :Main %* >>%AUTO_LOGFILE% 2>&1
goto :EOF

:Main
echo "Hello World"
rem The above echo will be printed to test.log

但是,如果目的是区分错误消息和正常输出,则可以通过以下技巧在同一屏幕中完成此操作:

代码语言:javascript
复制
"%~F0" %* 2>&1 1>&3 | findstr /N /A:4E "^"

这样,错误消息的前面会出现一个红色背景上的黄色行号。这种方法可以直接用于几种情况;例如,在任何编程语言源程序的编译中:

代码语言:javascript
复制
anycompiler %1 2>&1 1>&3 | findstr /N /A:4E "^"
票数 5
EN

Stack Overflow用户

发布于 2012-04-20 16:02:39

将这些行括在括号中

代码语言:javascript
复制
(
  REM How to do the stdout redirection from within the script itself here?
  ECHO is this redirected?
  ECHO yes it is
) >out.txt
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10239610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档