Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an environment variable is defined without command extensions and without using a batch file?

I need to use a cmd.exe command line (cmd.exe is being called from the gyp build tool) to determine whether an environment variable is defined or not. How can I do this? I am okay assuming that the variable value does not contain single or double quotes, but cannot assume that command extensions are enabled.

I've tried the following, which works great in a .bat file, but fails when typed directly on the command line:

IF "%UNDEFINED%" == "" (echo yes) 

When that exact line is in a .bat file and executed, I see yes as the output. When I type it on the command line, the output is empty. I am testing this on Windows XP SP3, though my coworker sees the same results on Windows 7. This is the method suggested by http://support.microsoft.com/kb/121170 and http://www.robvanderwoude.com/battech_defined.php. I do not want to use IF DEFINED UNDEFINED (echo yes) because that won't work if command extensions are disabled.

The top-voted answer in the following post has led me to believe that this issue is related to how percent-expansion is handled differently in the "CmdLineParser" vs. the "BatchLineParser," but still has not led me to a solution: How does the Windows Command Interpreter (CMD.EXE) parse scripts?

like image 321
Johann Avatar asked May 03 '13 21:05

Johann


People also ask

How do you check if an environment variable is set in Windows?

On WindowsSelect Start > All Programs > Accessories > Command Prompt. In the command window that opens, enter set. A list of all the environment variables that are set is displayed in the command window.

How do you check if a file exists or not in CMD?

Checking for the existence of a file can be accomplished by using IF EXIST in a batch file called from the login script, or by using the login script ERRORLEVEL variable with a MAP statement. The COMMAND.COM /C will close the CMD box window automatically after it terminates.

What is the command to see environment variables?

To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables.

What does %1 do in batch file?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.


1 Answers

Errr... just:

if defined your-var-name (      echo yarp ) else (     echo narp ) 

I should add, I do not believe this needs command extensions...

like image 91
Simon Catlin Avatar answered Sep 20 '22 18:09

Simon Catlin