Question

I was testing this code submitted by unclemeat in this question(UncleMeat referenced this site) when I tested it by inputting some carots(^) it produced some interesting results.

Len.bat

@echo off
setLocal EnableDelayedExpansion

set s=%1
set length=0

:count
if defined s (
    set s=%s:~1%
    set /A length += 1
    goto count
)

echo %length%

Testing of Len.bat

C:\Users\Public>len ^
More?
More?
0

C:\Users\Public>len ^^
12

C:\Users\Public>len ^^^
More?
More?
12

C:\Users\Public>len ^^^^
1

C:\Users\Public>len ^^^^^
More?
More?
1

C:\Users\Public>len ^^^^^^
13

C:\Users\Public>len ^^^^^^^
More?
More?
13

C:\Users\Public>len ^^^^^^^^
22

C:\Users\Public>

Ignoring the double More? where I simply returned without inputting anything, the pattern is:

  1. 0
  2. 12
  3. 12
  4. 1
  5. 1
  6. 13
  7. 13
  8. 22
  9. 22
  10. 13
  11. 13
  12. 2
  13. 2
  14. 14
  15. 14
  16. 23
  17. 23
  18. 14
  19. 14
  20. 23
  21. 23
  22. 14
  23. 14
  24. 23
  25. 23

Every odd occurance prompts me with the double More?, which is why it is doubled, but other wise these results are just wierd. I thought it would have to do something with the following line in the code, but there seems to be no relationship!

Any explanation to this irregular data? Or is this just one of those things about cmd....

Était-ce utile?

La solution

It has many reasons why the code completly fails with carets.
First the way you try to call your batch will fail.

A caret escapes the next character and is itself removed from the line.
A single caret at a line end escapes the line end (it's called multiline caret), that's the cause why cmd.exe show you the prompt More?. This will be true for all odd number of carets.

Sample with seven carets.

length ^^^^^^^
More?
More?

cmd.exe will call the length bat with the following string ^^^<newline>.
The newline will be split from the %1 parameter, so in %1 is only ^^^.

But now you this part fails completly

set s=%1
set length=0

As it expands to set s=^^^ set length=0

As the last caret is now a multiline caret it will append set length=0 to the line!

So in the variable s is now the content ^set length=0.
This will never work ...

Even in this block the %s:~1% will be a cause of further problems, as it will also can expand to multiline carets when s contains carets (when you use 8 carets length ^^^^^^^^).

if defined s (
    set s=%s:~1%
    set /A length += 1
    goto count
)

For some more explanations about the caret you can read SO:Long commands split over multiple lines in Vista/DOS batch (.bat) file

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top