Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file: suppress command error output when used in a for loop

Tags:

batch-file

I am iterating through the command output in a for loop. Consider the following code:

for /F "tokens=1 delims=?=" %%A in ('set __variable') do ( set %%A= )

Basically I am trying to clear the value of every environment variable whose name starts with "__variable". However, if no such variable is set, I get an error that says "Environment variable __variable not defined", which is not something that I would like displayed on my console. So naturally, I would change my code like this:

for /F "tokens=1 delims=?=" %%A in ('set __variable 2> NUL') do ( set %%A= )

But now I get a new error that says "2> was unexpected at this time." or something of that effect. Now I am stuck; is there a way for me to complete my objective without having the standard error show up on the screen?

like image 924
Dan Avatar asked Aug 24 '11 16:08

Dan


People also ask

How to use for loop in command prompt?

FOR /F. Loop command: against the results of another command. FOR /F processing of a command consists of reading the output from the command one line at a time and then breaking the line up into individual items of data or 'tokens'. The DO command is then executed with the parameter(s) set to the token(s) found.

What is f in batch script?

By default, /F breaks up the command output at each blank space, and any blank lines are skipped.

How do I loop a batch script only a certain amount of times?

There is an example: @echo off set loop=0 :loop echo hello world set /a loop=%loop%+1 if "%loop%"=="2" goto next goto loop :next echo This text will appear after repeating "hello world" for 2 times. Output: hello world hello world This text will appear after repeating "hello world" for 2 times.

What does f in cmd mean?

-f usually mean force a command, for example to force the remove of a folder with content ensted of rm -r myfolder/ we can force it by using rm -rf myfolder/


1 Answers

For Windows NT 4 and later, you will need to escape the pipe and redirection symbols, which is done by prefixing them with carets ( ˆ ):

for /F "tokens=1 delims=?=" %A in ('set __variable 2^>NUL') do ( set %A= )
like image 197
Andrey Kamaev Avatar answered Sep 24 '22 08:09

Andrey Kamaev