30

Back in the mid-90's, I remember doing something like this:

if %1==. dir

basically, if you put the above code in dodir.bat and run it on its own without passing it any parameters, it would run the dir command. However, if you passed it anything at all as a parameter, it would not run the dir command.

I can't seem to get this to work in my Windows 7 batch files. Perhaps I don't remember the proper syntax. Any helpers?

saw303
  • 8,051
  • 7
  • 50
  • 90
oscilatingcretin
  • 10,457
  • 39
  • 119
  • 206
  • a "catch all" example: http://stackoverflow.com/questions/830565/how-do-i-check-that-a-parameter-is-defined-when-calling-a-batch-file/34552964#34552964 –  Jan 01 '16 at 01:47

3 Answers3

70

if %1.==. dir will break if the parameter includes various symbols like ", <, etc

if "%1"=="" will break if the parameter includes a quote (").

Use if "%~1"=="" instead:

if "%~1"=="" (
    echo No parameters have been provided.
) else (
    echo Parameters: %*
)

This should work on all versions of Windows and DOS.

Unit Test:

C:\>test
No parameters have been provided.

C:\>test "Lots of symbols ~@#$%^&*()_+<>?./`~!, but works"
Parameters: "Lots of symbols ~@#$%^&*()_+<>?./`~!, but works"
Tolga
  • 2,643
  • 1
  • 27
  • 18
  • 2
    Could you elaborate or pass a reference on what %~1 does? – Josejulio May 16 '16 at 23:19
  • 1
    @josejulio You can do "call /?" to get the details on all the fancy things you can do with parameters. For %~1 it says: expands %1 removing any surrounding quotes (") – Tolga Nov 24 '16 at 16:50
25

Actually it was if %1.==. command (note the . after %1) back then. And you can use that now in Windows 7, it should work.

Example usage:

if %1.==. (
    echo No parameters have been provided.
) else (
    echo Parameters:
    echo %*
)
Sk8erPeter
  • 6,899
  • 9
  • 48
  • 67
Andriy M
  • 76,112
  • 17
  • 94
  • 154
  • What does the period stand for? – Rishabh Bhatnagar Dec 08 '20 at 08:38
  • 2
    @RishabhBhatnagar: I don't believe it stands for anything specific. It's there simply to avoid syntax error in case `%1` evaluates to an empty string. It could be some other character, and indeed I've seen others used (e.g. `if %1A==A`), but `.` has probably been used most often in this particular pattern. Note that this pattern was prevalent in the past, in the DOS era. Nowadays, `if "%~1"==""`, as [suggested by Tolga](https://stackoverflow.com/a/16819109/297408), would be the preferred method. – Andriy M Dec 08 '20 at 13:31
15

Try surrounding in quotes:

if "%1"=="" (
    echo "nothing was passed"
) else (
    echo "a parameter was passed"
    dir
)

You can take the echo's out, I just put them there for educational purposes.

dcp
  • 54,410
  • 22
  • 144
  • 164