user3683638
user3683638

Reputation: 25

if statement when environment variable exists/not exists in batch files

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!

Upvotes: 2

Views: 4651

Answers (2)

JosefZ
JosefZ

Reputation: 30113

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%"

==>

Upvotes: 3

Stephan
Stephan

Reputation: 56180

if exists checks for files.

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

Upvotes: 3

Related Questions