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)

5
  • Is setting var really necessary? You could just type tmp instead of setting and echoing var. Commented Oct 7, 2014 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 Commented Oct 7, 2014 at 13:40
  • operate on the whole file contents at once or line per line? Commented Oct 7, 2014 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" Commented Oct 7, 2014 at 13:50
  • For this see stackoverflow.com/questions/21245545/… . For reading 7th line use for /f "skip=6 tokens=*" %%v in (tmp) do ( echo %%v \n goto end ) Commented Oct 7, 2014 at 14:05

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.