Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if environment variables are defined in windows batch scripting [closed]

I am trying to create a batch file to check if the environment variables are defined or undefined and gives a certain output statement if it is or not. This is what I have and I can't seem to get the program to tell me that any argument is defined.

if not defined "%MyVar%" (
    echo MyVar is NOT defined
)

if defined "%MyVar%" (
    echo MyVar IS defined 
)
like image 314
DJezus Avatar asked Apr 10 '17 20:04

DJezus


People also ask

How can I test if my environment variable is working?

To Check if an Environment Variable ExistsSelect Start > All Programs > Accessories > Command Prompt. In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable. For example, to check if NUKE_DISK_CACHE is set, enter echo %NUKE_DISK_CACHE%.

How do I see Windows environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables.

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.

How do I see environment variables in Windows PowerShell?

Environment variables in PowerShell are stored as PS drive (Env: ). To retrieve all the environment variables stored in the OS you can use the below command. You can also use dir env: command to retrieve all environment variables and values.


1 Answers

I think you mean to write:

if not defined MyVar (
  echo MyVar is NOT defined
)

and

if defined MyVar (
  echo MyVar IS defined 
)

This is because cmd.exe will expand the reference to the content of the variable if you enclose it within % characters. (You want to know if the variable itself is defined, not if a variable with the name of the content of that variable is defined.)

Note that environment variables (names within % characters) are different from replaceable parameters (%0, %1, etc.).

I would recommend switching to Windows PowerShell, because it has built-in parameter parsing features, variable scopes, real functions, and much, much more.

like image 197
Bill_Stewart Avatar answered Sep 23 '22 12:09

Bill_Stewart