Radoslaw Krasimirow
Radoslaw Krasimirow

Reputation: 1873

How to make a conditional lable call in batch

I want to make a simple batch script that should be able to run ant build script. When I start the batfile I want it to prompt me for target name. Then to do a simple conditional test: IF I just type enter (without entering any string) to GOTO a lable1, ELSE to GOTO the lable2 (wich calls the ant with argument, what I have entered at the promt). So this is what I tried with but didn't work:

@echo off

set /p target=Please enter target:  

IF %target%=="" (GOTO Call_script_with_default_target) ELSE (GOTO     Call_script_with_specified_target)

:Call_script_with_default_target
echo ant default-target
::when no argument is present, it assumes default target
ant 
pause
GOTO End

:Call_script_with_specified_target
echo ant %target%
ant %target%
GOTO End

:End
pause

When I type clean (at prompt) it works as expected, but when I just hit enter nothings happen.

Upvotes: 0

Views: 43

Answers (3)

Bloodied
Bloodied

Reputation: 975

You can use "if defined variable" or "if not defined variable" as such:

@echo off

set /p target=Please enter target:  

 if not defined target (
  echo ant default-target
  ant 
  pause
  goto :EOF
) else (
  echo ant %target%
  ant %target%
  pause
  goto :EOF
)

Upvotes: 1

JosefZ
JosefZ

Reputation: 30153

The facts:

  • set /p target=Please enter target: command keeps value of target variable unchanged if user just hits enter;
  • %target% evaluates to empty string if not initialised. Hence, IF %target%=="" (... evaluates to syntactically wrong IF =="" (... and raises an error.

Either use IF "%target%"=="" (..., or simplify your script to equivalent

@echo off

set "target="
set /p target=Please enter target:  

call ant %target%

:End
pause

Upvotes: 2

MC ND
MC ND

Reputation: 70943

Include the quotes in BOTH sides of the test.

IF "%target%"=="" ...

Or check if the variable holds something

if defined target ...

Or detect if the set /p operation failed

set /p "target=Please enter target:"  || GOTO Call_script_with_default_target

Upvotes: 1

Related Questions