How to check if a variable exists in a batch file?

I am using the call command:

call beingcalled.bat randomnumber

In beingcalled.bat:

@echo off
set call=%1
echo %call%
set call=%call%%call%
call caller.bat %call%`

In caller.bat:

@echo off
set calltwo=%1
echo %calltwo%
if "%calltwo%"== "" (
    echo Error
) else (
    call beingcalled.bat randomnumber
)

Why does the command if "%calltwo%"== "" not work? And how do I see if a variable was set?


IF "%Variable%"=="" ECHO Variable is NOT defined

This should help but this works, provided the value of Variable does not contain double quotes. Or you may try. Both worked for me.

VERIFY OTHER 2>nul
SETLOCAL ENABLEEXTENSIONS
IF ERRORLEVEL 1 ECHO Unable to enable extensions
IF DEFINED MyVar (ECHO MyVar IS defined) ELSE (ECHO MyVar is NOT defined)
ENDLOCAL

source http://www.robvanderwoude.com/battech_defined.php


The easiest way is just using the command line extension DEFINED. This is also my preferred way of doing this.

in your case:

@echo off
set calltwo=%1
echo %calltwo%
if defined calltwo (
echo Error
)else (
call beingcalled.bat randomnumber
)

If this doesn't work for you there is a workaround in the link below.

The question is also a duplicate of: Check if an environment variable is defined without command extensions and without using a batch file?


This is just a follow-up to the comment (and bounty) post by @Rishav

Here’s a trick I picked up a very long time ago:

@ECHO OFF

SET Foo=%1

ECHO ==  Start  ====================

ECHO %Foo%

IF %Foo%x == x ECHO Parameter not set

ECHO ==  End  ====================
ECHO.

If the parameter is not set, you get a check of x==x

If the parameter is set (to, say, “asdf”), you get a check of asdfx==x


None of these solutions work for me on windows 10, but I did find a solution that does work

IF %foo%==^%foo^% ECHO variable not defined