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

Sac*_*n S 3 batch-file

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

#!/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
Run Code Online (Sandbox Code Playgroud)

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

test.sh
Run Code Online (Sandbox Code Playgroud)

代替:

test.sh >> test.log 2>&1    
Run Code Online (Sandbox Code Playgroud)

我试图在批处理脚本中做类似的事情.我的批处理代码如下:

@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?
Run Code Online (Sandbox Code Playgroud)

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

exec 3>&0 4>&1 >>$AUTO_LOGFILE 2>&1
Run Code Online (Sandbox Code Playgroud)

Aac*_*ini 5

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

@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
Run Code Online (Sandbox Code Playgroud)

Adenddeum:

我认为OP希望 stdout与stderr 分开以在屏幕上看到错误消息,但也许我误解了他.要将stdout和stderr发送到文件,请使用下面的行作为dbenham在他的评论中指出:

"%~F0" %* >>%AUTO_LOGFILE% 2>&1
Run Code Online (Sandbox Code Playgroud)

或者以上面评论中已经提到的更简单的方式:

@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
Run Code Online (Sandbox Code Playgroud)

但是,如果目的是从正常输出中解决错误消息,那么可以通过此技巧在同一屏幕中完成:

"%~F0" %* 2>&1 1>&3 | findstr /N /A:4E "^"
Run Code Online (Sandbox Code Playgroud)

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

anycompiler %1 2>&1 1>&3 | findstr /N /A:4E "^"
Run Code Online (Sandbox Code Playgroud)