I wonder is there any way to check that if a label exist in a batch file?
If %input%=ABC (
If Label ABC Exists (
Goto ABC
)
)
How
Here is a refined, more robust version of the MC ND answer. (The original answer, his edit addresses many of these same points).
Labels are case insensitive, so the search should be case insensitive.
A valid label may have additional text after the label, so there are two searches required. The additional text is frequently used as documentation. For example: :label documentation
is still a valid label.
findstr /ri /c:"^ *:%input% " /c:"^ *:%input%$" "%~f0" >nul 2>nul && goto %input%
The above should work in most situations, but there are a few unlikely conditions that could cause it to fail.
Any of the following characters can appear before the label - ,
;
=
<0x255>
. They all are treated as spaces when they precede a label. But the search above only allows for
. A [class]
expression could be used, but including
and <0x255>
can be awkward.
In a similar fashion, the label can be terminated by some characters other than
(a different list).
The label could contain regular expression meta-characters.
The FINDSTR $
anchor only recognizes
as end of line, so the search can fail if the script uses Unix style
line endings.
The search could be refined to handle most of the above conditions. But it is simpler to simply avoid those conditions in your code. I don't think it is possible to define a bullet proof search using a single FINDSTR. A bullet proof search would require at least two FINDSTRs, and one would have to use the /G:file
option - yuck.