How to check command line parameter in “.bat” file?

后端 未结 7 2053
无人共我
无人共我 2020-12-13 02:00

My OS is Windows Vista. I need to have a \".bat\" file where I need to check if user enters any command-line parameter or not. If does then if the parameter equals to

相关标签:
7条回答
  • 2020-12-13 02:35

    Actually, all the other answers have flaws. The most reliable way is:

    IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
    

    Detailed Explanation:

    Using "%1"=="-b" will flat out crash if passing argument with spaces and quotes. This is the least reliable method.

    IF "%1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
    
    C:\> run.bat "a b"
    
    b""=="-b" was unexpected at this time.
    

    Using [%1]==[-b] is better because it will not crash with spaces and quotes, but it will not match if the argument is surrounded by quotes.

    IF [%1]==[-b] (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
    
    C:\> run.bat "-b"
    
    (does not match, and jumps to UNKNOWN instead of SPECIFIC)
    

    Using "%~1"=="-b" is the most reliable. %~1 will strip off surrounding quotes if they exist. So it works with and without quotes, and also with no args.

    IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
    
    C:\> run.bat
    C:\> run.bat -b
    C:\> run.bat "-b"
    C:\> run.bat "a b"
    
    (all of the above tests work correctly)
    
    0 讨论(0)
提交回复
热议问题