Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect a FOR command in Windows batch

Tags:

batch-file

I know how to redirect a Windows shell command with the >|>>|<|<< operators, but I cannot accomplish it for commands used inside a FOR command?

For instance:

for /f "usebackq tokens=*" %%I in (`__COMMAND__ 2>nul`) do (
    set MYVAR=%%I
)

You see, here I would like to silent the stderr of this __COMMAND__. The shell complaints that it does not expect a 2 in that place (same behaviour for other redirections).

Anybody can help here?

like image 859
Campa Avatar asked Feb 23 '16 14:02

Campa


People also ask

How do you redirect the output of a command to a file in batch?

Redirect the Standard Output to a Text File From Within a Batch File. To redirect the standard output to a text file, add the redirection operator between the command and the text file, as shown in the syntax below. For example, we have to redirect the output of the command powercfg to a text file named stdoutput. txt ...

How do I redirect a command file?

To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.

What is %% A in batch?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.


1 Answers

for /f "usebackq tokens=*" %%I in (`__COMMAND__ 2^>nul`) do (
    set MYVAR=%%I
)

in this case redirection and conditional execution operators need to be escaped with caret.

Or put everything in double quotes :

for /f "usebackq tokens=*" %%I in (`"__COMMAND__ 2>nul"`) do (
    set MYVAR=%%I
)

Using delayed expansion is also possible:

@echo off

setlocal enableDelayedExpansion

set "command=__COMMAND__ 2>nul"

for /f "usebackq tokens=*" %%I in (`!command!`) do (
    set MYVAR=%%I
)
like image 99
npocmaka Avatar answered Sep 28 '22 14:09

npocmaka