Search code examples
batch-fileif-statementnetstat

BATCH - netstat command in IF statement


SET con = netstat -a -n | find "127.0.0.1:3306"
if "%con%" == "" (
    telnet 127.0.0.1 3306
)
pause

This will always execute telnet.

Actually when I look manually for netstat -a -n | find "127.0.0.1:3306" it isn't equal to "" but %con% is always set to "", why?.

What I am doing wrong?


Solution

  • You could try something like this instead.

    netstat -a -n |find "127.0.0.1:3306" >nul
    if ERRORLEVEL 1 (
    telnet 127.0.0.1 3306
    )
    

    Your approach looks like a generic Linux shell solution, but Windows batch is nowhere near as useful or flexible.

    The approach above uses the return code from 'find' to determine whether or not to run telnet.

    One thing that messed me up for a while is that ERRORLEVEL <number> works like ERRORLEVEL GE <number> not ERRORLEVEL EQ <number>, so ERRORLEVEL 0 is always true.