3

I want to check if a certain environment variable is set in the PC. If yes do x if not do y.

I tried these and some variations of them:

IF EXISTS %SIGN% runtest.exe --redirect -l %NAME%
ELSE runtest.exe -l %NAME%

if "%SIGN%" == "" runtest.exe --redirect -l %NAME%
ELSE runtest.exe -l %NAME%

None of them work well in both cases (when the environment variable SIGN exists and when it doesn't exist). Sometimes just in one case...

Please can you help? Thanks!

2
  • 1
    if exists checks for files. for variables do: if defined sign (without the percent-signs Commented Apr 1, 2015 at 12:17
  • @Stephan - make this an answer. Commented Apr 1, 2015 at 12:25

2 Answers 2

4

IF Conditionally perform a command

IF DEFINED SIGN (
     runtest.exe --redirect -l %NAME% 
) ELSE (
     runtest.exe -l %NAME%
)

or shortly

IF DEFINED SIGN (runtest.exe --redirect -l %NAME%) ELSE (runtest.exe -l %NAME%)

Valid syntax:

  • all ), ELSE and ( must be on an only line as follows: ) ELSE (

Note:

if DEFINED will return true if the variable contains any value (even if the value is just a space).

According to above predicate, IF DEFINED SIGN condition seems to be equivalent to reformulated test if NOT "%SIGN%"=="" but it is valid in batch only, where %undefined_variable% results to an empty string:

if NOT "%SIGN%"=="" (runtest.exe --redirect -l %NAME%) ELSE (runtest.exe -l %NAME%)

Otherwise, in pure CLI, %undefined_variable% results to %undefined_variable%

Proof:

==>type uv.bat
@echo undefined_variable="%undefined_variable%"

==>uv.bat
undefined_variable=""

==>echo undefined_variable="%undefined_variable%"
undefined_variable="%undefined_variable%"

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

Comments

3

if exists checks for files.

For variables do: if defined sign (without the percent-signs)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.