开发者

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 fil开发者_开发知识库es. Perhaps I don't remember the proper syntax. Any helpers?


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"


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 %*
)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜