Parameter handling in MS-DOS is weak by default, so here's a routine I stole from an old colleague (Jimmy, if you ever read this, pleas shut up. And I guess you stole it from someone first! ;)
First, set up the internal variables needed. The first gets the dir the script is run from, the second the name of the script:
set BASEDIR=%~dp0I put the Usage-description early so it's easily readable within the script. Note the ^-signs to allow special chars within echo:
set BASENAME=%~n0
goto GET_PARAMETERSStart of parameter loop, with a label. I always put the "help"-flag first out of convenience:
:USAGE
echo Usage:
echo %BASENAME% ^/f ^/v
echo ^/f file : enter file with full path
echo ^/v : verbose mode
goto END
:GET_PARAMETERSFor each parameter, enter a block in the following way. Check first parameter for the current flag, if found then set a variable and "shift out" from parameter stack and start over. If not found, go to next parameter.
:HELP
if /i [%1] neq [/?] goto FILE
goto USAGE
:FILEIf the parameter is a flag only like in the following case, only one shift is needed:
if /i [%1] neq [/f] goto VERBOSE
set FILE=%2
shift
shift
goto GET_PARAMETERS
:VERBOSE
if /i [%1] neq [/v] goto ENDPARAM
set VERBOSE=1
shift
goto GET_PARAMETERS
End of parameter loop, check for any other parameters that aren't covered above and give error message if found:
:ENDPARAMValidate parameters that are mandatory:
if [%1] equ [] goto VALIDATE_PARAMETERS
echo Error! Incorrect parameters given
goto USAGE
:VALIDATE_PARAMETERSStart the actual script (finally!). Don't forget the end-label at bottom:
:: Check for mandatory parameters
if /i [%FILE%] neq [] goto EXECUTION
echo Error! Missing parameter Version
goto USAGE
:EXECUTION
...
:ENDWhat does this give you? Well, most importantly you don't need to enter parameters in any order and you only allow prescripted input. As a bonus, you get help and usage description.
If you think it's awkwars, all I can say is that MS-DOS is awkward to script in ;).
Here's the script in one go, for easy copy-paste:
set BASEDIR=%~dp0
set BASENAME=%~n0
goto GET_PARAMETERS
:USAGE
echo Usage:
echo %BASENAME% ^/f ^ /v
echo ^/f file : enter file with full path
echo ^/v : verbose mode
goto END
:GET_PARAMETERS
:HELP
if /i [%1] neq [/?] goto FILE
goto USAGE
:FILE
if /i [%1] neq [/f] goto VERBOSE
set FILE=%2
shift
shift
goto GET_PARAMETERS
:VERBOSE
if /i [%1] neq [/v] goto ENDPARAM
set VERBOSE=1
shift
goto GET_PARAMETERS
:ENDPARAM
if [%1] equ [] goto VALIDATE_PARAMETERS
echo Error! Incorrect parameters given
goto USAGE
:VALIDATE_PARAMETERS
:: Check for mandatory parameters
if /i [%FILE%] neq [] goto EXECUTION
echo Error! Missing parameter Version
goto USAGE
:EXECUTION
...
:END
No comments:
Post a Comment