user972276
user972276

Reputation: 3053

if/else redirect output to empty variable in batch file

Here is my code:

IF "%LOGFILE%" NEQ "" (
    CALL :DO_SOMETHING 2>&1> %LOGFILE%
) ELSE (
    CALL :DO_SOMETHING
)

The issue I am facing is that the IF/ELSE statement is treated as one big statement and the statement as a whole needs to be syntactically correct. So if "%LOGFILE%" does equal "", the first CALL statement would not be syntactically correct (even though it would never get called in this scenario), making the whole IF/ELSE statement syntactically incorrect.

How can I get around this issue?

Upvotes: 1

Views: 886

Answers (2)

RGuggisberg
RGuggisberg

Reputation: 4750

Another way:

SET logfile_redirection=2>&1> %LOGFILE%
IF "%LOGFILE%"=="" SET "logfile_redirection="
CALL :DO_SOMETHING %logfile_redirection%

Quotes for SET are not required, but ensures that there are no trailing spaces.

Upvotes: 0

Harry Johnston
Harry Johnston

Reputation: 36328

IF "%LOGFILE%" NEQ "" (
    SET logfile_redirection=2^>^&1^> %LOGFILE%
) ELSE (
    SET logfile_redirection=
)
CALL :DO_SOMETHING %logfile_redirection%

Upvotes: 4

Related Questions