And here comes the expansion. Please note that your code is pretty close to perfect, and these tips only encourage good scripting habits.
To begin with, you spelt variable
as varible
in line 3
of the :HELP
label.
First line of the :RUN
label:
set /a counter=%counter% + 1
Instead of this, one can do
set /a counter+=1
This isn't incredibly helpful at the moment, but when you want to add a variable to another variable...
set /a varA+=%varB%
This also works for other operators...
set /a varA*=%varB%
And slightly more complex equations...
set /a varA-=%varB% * %varC%
Which will evaluate %varB% * %varC%
, then subtract the result from varA
The command CMD /C "%COMMAND%"
is not entirely necessary to my knowledge - simply writing %COMMAND%
on a new line will cause the batch parser to expand it, so if %COMMAND%
is set as exit
, the line will read, at run time, exit
. This enables you to use this method rather than the entire CMD /C
method.
Another concern that could become more than just a concern is your method for checking the errorlevel
- there's a problem. Checking with quotes and ==
denotes a string comparison - never good when you're dealing with two numbers. So you'll need a fix for this problem, and luckily it's quite simple.
if %errorlevel% EQU 1 ( ... )
This tests for a mathematical equivalence - always good when you're dealing with two numbers. All the operators for mathematical equivalencies are...
EQU - 'equal to'
GTR - 'greater than'
LSS - 'less than'
GEQ - 'greater than or equal to'
LEQ - 'less than or equal to'
And finally, using if varA==varB (goto label)
is not necessary - it works just as well as if varA==varB goto label
. The only time you need brackets is when you plan on conditionally executing multiple lines or if you need to use else
(just to be safe). When using brackets, always remember to balance them. Indenting isn't required, but it gets really confusing when you start nesting if
statements and for
loops without it. An example of executing multiple lines...
if %varA% GTR %varB% (
echo varB is less than varA
if %varA% GTR %varC% (
echo varC is less than varA
) else (
echo varC is greater than varA
)
To conclude, your code obviously works fine, but some habits die hard in weird circumstances later on, so it's best to get used to using common conventions (they exist for a reason!). As a side note, remember that batch scripting is not case sensitive. Anything I wrote here, along with anything you wrote, can be written in the opposite case - it has no difference.