Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a variable in a FOR loop that is involved in a pipe?

I know this question has been ask many times, but I've read the answers for hours and tried everything, nothing seems to work. Basically I can't succeed to (Re-)SET a variable in a for /F loop.

I would like to do the following : check the connection between two computers and do an action (basically start a program) if the connection doesn't exist anymore.

@ECHO OFF

SET _A=0

PING localhost | (for /F "tokens=*" %%a in ('FINDSTR Reply') DO @ECHO %%a & SET _A=1)

if %_A%==0 ECHO %_A% FAIL
if %_A%==1 ECHO %_A% SUCCESS

PAUSE

Here I assume that if the PING command doesn't return at least once the word "Reply", then the connection was lost.

The first "DO @ECHO %%a" works, but then it doesn't reset the variable "_A". And I need this variable to be external to the FOR loop because after that the "if %_A%==1" will have to execute the program only once.

Anyone knows what I'm doing wrong ? Thanks a lot for your help. I really tried everything, included setlocal enabledelayedexpansion and putting variable between !!, but nothing works, it always ends up printing "FAIL" and never "SUCCESS".

like image 806
ccflash Avatar asked Jan 17 '26 19:01

ccflash


1 Answers

This is a great question! The problem is the pipe | as this initialises separate termporary cmd instances for both sides. The variable _A is set in the right instance but is lost afterwards.

If you do:

for /F "tokens=*" %%a in ('PING localhost ^| FINDSTR Reply') do @ECHO %%a & SET _A=1

it will work as the set command is in the main cmd instance the batch script is running in.

Note the escaped pipe ^|, which is necessary to transfer its execution to the cmd instance created by for /F for the command line it parses.

like image 173
aschipfl Avatar answered Jan 20 '26 23:01

aschipfl