Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows 7 batch files: How to check if parameter has been passed to batch file

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?

like image 631
oscilatingcretin Avatar asked Apr 20 '11 18:04

oscilatingcretin


People also ask

What is == in batch file?

[ == ] (Double Equals) The "IF" command uses this to test if two strings are equal: IF "%1" == "" GOTO HELP. means that if the first parameter on the command line after the batch file name is equal to nothing, that is, if a first parameter is not given, the batch file is to go to the HELP label.

What does %% A mean in batch file?

%%a refers to the name of the variable your for loop will write to. Quoted from for /? : FOR %variable IN (set) DO command [command-parameters] %variable Specifies a single letter replaceable parameter. (set) Specifies a set of one or more files. Wildcards may be used.

What does && do in batch file?

&& runs the second command on the line when the first command comes back successfully (i.e. errorlevel == 0 ). The opposite of && is || , which runs the second command when the first command is unsuccessful (i.e. errorlevel != 0 ).


2 Answers

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" 
like image 134
Tolga Avatar answered Sep 17 '22 13:09

Tolga


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 %* ) 
like image 37
Andriy M Avatar answered Sep 17 '22 13:09

Andriy M