Can I use labels inside IF?

Microsoft Windows
Post Reply
User avatar
MigrationUser
Posts: 336
Joined: 2021-Jul-12, 1:37 pm
Contact:

Can I use labels inside IF?

Post by MigrationUser »

24 Apr 2012 14:42
npocmaka


Because it seems I cant:

Code: Select all

if exist c:\ (
	goto :myLabel
	:mylabel
)
prints:

) was unexpected at this time.

I can workaround this with subroutine but it's strange.
I have no problems with going to labels outside the IF.

----------------------------

#2 24 Apr 2012 14:57
jeb


There are two different problems here.

1) A GOTO inside of brackets breaks the bracket context (and stops a FOR-Loop)

Code: Select all

if 1==1 (
  goto :next
  echo never reached
:next
  echo After the label
) ELSE (
  echo Why I can see this?
)
Outputs

Code: Select all

After the label
Why I can see this?
As you can see the ELSE isn't effective anymore after invoking the GOTO

2) Labels are a bit strange inside of brackets
Labels in brackets use always two lines
- The primary line is the label, here is also a :: Label allowed
- The secondary line (after a label) must be a VALID statement or and label (but not a :: comment), an empty line or a closing bracket isn't valid here

In the secondary line are also the special characters active like "&|>"

Code: Select all

(
:NormalLabel & echo this will not be executed
:SecondaryLine & echo This will be executed
)
As you can see, it's all obvious smile

jeb

----------------------------

#3 24 Apr 2012 15:23
npocmaka


IT'S ALIVE!

..I mean it works with two labels.Thanks a lot :-) .

And it's not so obvious.I still do not understand why with two labels the bracket context works.But anyway it works .

----------------------------

#4 04 Nov 2012 23:08
carlos


Mix the character & with labels are confusing:

Code: Select all

(
:Label1 & echo line1
:Label2 & echo line2
)
prints:

Code: Select all

line2
But:

Code: Select all

(
:Label1
echo line1
:Label2
echo line2
)
prints:

Code: Select all

line1
line2
----------------------------

#5 05 Nov 2012 18:53
dbenham


@Carlos - Oooh, that is pure evil. I like it! :twisted:

----------------------------

#6 06 Nov 2012 09:35
jeb


Long time ago there was a discussion about labels inside barckets.
Nested for loop recursing directories
and here
SO: windows batch file with goto command not working

And there exists a more evil construct.

Code: Select all

for %%a in (1 2 3) DO (
:label1 ^
::label2
:label3
::Label4 ^

NeverEver^
(^ AlwaysWorks echo %%a)
)
It will show the numbers 1 to 3 (obviously) smile

Ok the code it's a bit obfuscated, but a little bit fun must be. smile

Btw. I'm happy that I recover my lost sample, as it's the only known way (for me),
to remove a single token form the beginning of a line.

jeb

Last edited by jeb (06 Nov 2012 09:38)
----------------------------
See also https://ss64.org/viewtopic.php?f=2&t=120
Post Reply