0

I'm trying to create a simple batch script that stores the output of a command to tmp file, stores the content of the tmp file to a variable, and outputs the variable:

@setlocal enableextensions enabledelayedexpansion
@echo off

ping -n 1 10.1.0.2 > tmp

SET @var= < tmp
ECHO %@var%

del tmp

I would expect the above to work, but it outpus:

C:\Documents and Settings\Administrator\Desktop>pinger.bat
ECHO is off.

(Nb: taking the @echo off just outputs ECHO is on, including echoing all the lines of code)

Juicy
  • 11,840
  • 35
  • 123
  • 212
  • Is setting var really necessary? You could just ```type tmp``` instead of setting and echoing var. – rostok Oct 07 '14 at 13:38
  • @rostok Yes I need it set in a var, outputting the contents of the file is not the goal of my program. I will then need to operate on the output – Juicy Oct 07 '14 at 13:40
  • operate on the whole file contents at once or line per line? – rostok Oct 07 '14 at 13:47
  • I will need to look at the 7th line of the output `Packets: Send = 1, Received = 1....` and check the tokens, namely make sure that `Received = 1`. The end goal of my program is to print "Host is up" or "Host is down" – Juicy Oct 07 '14 at 13:50
  • For this see http://stackoverflow.com/questions/21245545/ping-test-using-bat-file-trouble-with-errorlevel . For reading 7th line use ```for /f "skip=6 tokens=*" %%v in (tmp) do ( echo %%v \n goto end ) ``` – rostok Oct 07 '14 at 14:05

1 Answers1

1

The question pointed by @rostok (my answer here), shows the reason to not use the received packets to determine if the host is or not online. On the same subnet, over ipv4, with an offline host, you will get a "unreachable" error, but the packets are received.

For a simple test in ipv4, the linked answer can handle your problem. For a more robust test over ipv4 or ipv6 (that show different behaviour), this could help.

Anyway, the code to get the required data directly from the ping command,

set "received="
for /f "skip=6 tokens=5 delims==, " %%a in ('ping -n 1 10.1.0.2') do (
    if not defined received set "received=%%a"
)

or from the file

set "received="
for /f "usebackq skip=6 tokens=5 delims==, " %%a in ("tmpFile") do (
    if not defined received set "received=%%a"
)

Where the skip clause indicates that the first six lines should be skipped, and the tokens and delims select the required element inside the line

Packets: Send = 1, Received = 1,
        ^    ^^^ ^^        ^^^ ^  Delimiter position
1        2      3  4          5   Token number

But as said, this is not a reliable way to solve the problem

Community
  • 1
  • 1
MC ND
  • 69,615
  • 8
  • 84
  • 126