Batch file for parsing command line input that contains comma separated values
batch-file, command-line, command-line-arguments
Solution
Batch uses any combination of space, comma, semicolon, tab, and equal to delimit parameters. If you want to include any of those characters in a parameter, then the parameter must be quoted.
runUtility.cmd -A -B "x,y,z" -C w
Your script can remove the enclosing quotes with the `~` modifier. It is also a good idea to enclose your entire assignment within quotes to guard against problem characters like `&`, `|`, etc. The double quotes in the assignment below will not be included in the value.
set "argumentValue=%~2"
I developed an option parser that you might want to look at: Windows Bat file optional argument parsing.
The parsing code hardly changes regardless what options you define. The only things that have to change are the definition of your options using a single variable, the `SHIFT /3` should be modified to `SHIFT /1`, every `%~3` becomes `%~1`, and `%~4` becomes `%~2`.
The option parser has the ability to automatically supply default values for unspecified options.
Assuming you do not have default values, your options would be defined as
set "options=-A: -B:"" -C:"""
Meaning an `-A` option that does not take a value, and `-B` and `-C` options that take values but by default are undefined.
The options are stored in variables that match the option name (dash included).
Problem
I am working on a command line utility that takes set of input parameters as command. Those input parameters are then validated against predefined names. The utility is invoked in this manner: runUtility.cmd -A -B x,y,z -C w Here parameters are A, B and C (one that starts with -). Now the validation rules are as follows: Parameter's name should match predefined names, so that one can not pass any invalid parameter say -UVW Parameter may or may not have a value. In above example -A has no value, while -B has x,y,z and -C has w. I have written this code to validate the inputs: ``` :validate set argument=%1 set argumentValue=%2 if "%argument%" == "-A" ( shift goto validate ) if "%argument%" == "-B" ( if "%argumentValue%" == "" ( echo Empty value for -B goto end ) shift shift goto validate ) if "%argument%" == "-C" ( if "%argumentValue%" == "" ( echo Empty value for -C goto end ) shift shift goto validate ) if %argument%" == "" ( goto end ) Argument %argument% is invalid :end ``` But this does not seem to work, as -B has comma separated values, so for B when it does two shifts, in the next iteration, y becomes %1 and z becomes %2. Since y is not a parameter, it fails with last line of code that "Argument y is invalid". Actually comma is taken as delimiter by SHIFT command, so x,y,z does remain a single value. I want x,y,z to be taken as a single value OR is there any other way to process this? I am bit new to batch scripting , I tried with FOR loop but there I was not able to get %1 and %2 together in every iteration.