Package. How can I redirect stderr and stdout from the script package itself?

In Unix shell scripts, you can redirect stderr and stdout from the script itself, as shown 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 fact, test.sh can be executed simply as:

 test.sh 

Instead:

 test.sh >> test.log 2>&1 

I am trying to do similar in a script package. My batch code is as follows:

 @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 the script package itself? I'm more interested in converting this unix shell script statement to equivalent batch code:

 exec 3>&0 4>&1 >>$AUTO_LOGFILE 2>&1 
+3
source share
2 answers

The batch file test.bat below is functionally equivalent to your Unix script, that is, it sends all the standard output to a log file and displays an error on 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 wanted to separate stdout from stderr to see error messages on the screen, but maybe I misunderstood it. To send both stdout and stderr to a file, use the following line: dbenham noted in his comment:

 "%~F0" %* >>%AUTO_LOGFILE% 2>&1 

Or in an even simpler way, already expressed in the 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 goal is to delete error messages from the normal output, then this can be done on the same screen using this trick:

 "%~F0" %* 2>&1 1>&3 | findstr /N /A:4E "^" 

Thus, error messages precede a yellow line number on a red background. This method can be directly used in several cases; for example, in compiling any source program in a programming language:

 anycompiler %1 2>&1 1>&3 | findstr /N /A:4E "^" 
+5
source

Freeze strings 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 
+1
source

Source: https://habr.com/ru/post/1482858/


All Articles