Reputation: 396
In Unix shell scripting it is possible to redirect the stderr and stdout from the within script itself as below:
#!/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
In effect, test.sh can be executed simply as:
test.sh
Instead of:
test.sh >> test.log 2>&1
I am trying to do the similar in batch script. My batch code is as below:
@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?
How can I redirect stderr and stdout from within the batch script itself? What I'm more interested in is converting this unix shell script statement into equivalent batch code:
exec 3>&0 4>&1 >>$AUTO_LOGFILE 2>&1
Upvotes: 3
Views: 6737
Reputation: 67296
The test.bat Batch file below is functionally equivalent to your Unix script, that is, it send all standard output to the log file and error output to the screen:
@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
Adenddeum:
I thought the OP wants to separate stdout from stderr to see error messages in the screen, but perhaps I misunderstood him. To send both stdout and stderr to the file, use the line below as dbenham noted in his comment:
"%~F0" %* >>%AUTO_LOGFILE% 2>&1
Or in the even easier way already suggested in a comment above:
@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
However, if the purpose is to distingish error messages from normal output, then it may be done in the same screen via this trick:
"%~F0" %* 2>&1 1>&3 | findstr /N /A:4E "^"
This way the error messages appears preceded by a line number in yellow color on red background. This method may be directly used in several cases; for example, in the compilation of any programming language source program:
anycompiler %1 2>&1 1>&3 | findstr /N /A:4E "^"
Upvotes: 5
Reputation: 29369
Enclose the lines in parentheses
(
REM How to do the stdout redirection from within the script itself here?
ECHO is this redirected?
ECHO yes it is
) >out.txt
Upvotes: 1