0

The following simple batch file doesn't work as expected. It's meant to accept an argument, and if none is supplied, it uses a default value ("default", in this case).

Instead, if there is no argument supplied, it assigns an empty string to the variable Arg.

Test.bat:

@echo off
set Arg=%1
if "%Arg%"=="" (
    set Arg=Default
    echo No Arg, so use default value=%Arg%
) else (
    echo Arg=%Arg%
)
pause

The output of Test.bat is:

No Arg, so use default value=
Press any key to continue . . . 
Boann
  • 48,794
  • 16
  • 117
  • 146
Joe Marfice
  • 151
  • 2
  • 18

4 Answers4

2

Use

setlocal enabledelayedexpansion

and then !Arg! instead of %Arg% within the block. And read help set which explains all this.

Joey
  • 344,408
  • 85
  • 689
  • 683
1

Try

@echo off
set Arg=%1
if not defined arg set Arg=Default&echo No Arg, so use default
echo Arg=%Arg%

The problem is that within a block (parenthesisied series of statements) variables are resolved at PARSE time - before the instructions are executed.

@echo off
set Arg=%1
if not defined arg set Arg=Default&call echo No Arg, so use default=%%arg%%
echo Arg=%Arg%

if you really want the default to be displayed on the report line.

Magoo
  • 77,302
  • 8
  • 62
  • 84
0
@echo off

if [%1] == [] (
   set Arg=Default
) else (
   set Arg=%1
)
@echo Arg=%Arg%

Reference: How to check command line parameter in ".bat" file?

Community
  • 1
  • 1
DannyK
  • 1,342
  • 16
  • 23
0
@echo off
set arg=default
if not "%~1"=="" set "arg=%~1"
echo arg is ""%arg%"
foxidrive
  • 40,353
  • 10
  • 53
  • 68