Wason
Wason

Reputation: 1493

windows batch file loop in strings

I want to judge if input para is valid, and have a list of valid strings(saying "aaa","bbb","ccc","ddd" is correct), but I dislike to use if-else. I want a simple method to do this. I like something such as:

set env=%1
for %%A in ("aaa" "bbb" "ccc" "ddd" ) do if "%env%"==%%A echo true else goto end

I don't know how to make this out.

What I want is like:

set env=%1
if "%env%"neq"aaa" and "%env%"neq"bbb" and "%env%"neq"ccc"and "%env%"neq"ddd" (
    goto end
)

Thank aschipfl and magoo.

My resolution is as:

for %%a in (aaa bbb ccc ddd ) do (
   if "%env%"=="%%a" (
    goto next    
   ) 
)
@echo Wrong parameter! 
goto end
:next

Upvotes: 0

Views: 219

Answers (2)

aschipfl
aschipfl

Reputation: 34899

At first, I want to point out a basic issue of the if/else clause:

if "%env%"==%%A echo true else goto end

The parser treats the entire portion after the comparison expression as a single command line, hence if the comparison is positive, true else goto end is going to be echoed. To solve that you need to show the parser where the if statement ends by placing parentheses, like this...:

if "%env%"=="%%~A" (echo true) else goto end

...or this, if you want to spread it over multiple lines:

if "%env%"=="%%~A" (
    echo true
) else (
    goto end
)

In addition, I replaced %%A by "%%~A" to ensure that the right part of the comparison expression is always placed within quotes even in case you provided a list of strings like "aaa" bbb "ccc" ddd.


As far as I understand you want to go to :end in case the first argument %1 does not match any of the given strings. There is a logical error in your code, because you will always jump to :end even if a match has been encountered (as there are still three mismatches then), so the else clause is for sure going to be executed (supposing you corrected the if/else syntax as described earlier).

You could change the code as follows (using a FLAG variable indicating that a match has been found):

set "FLAG="
for %%A in ("aaa" "bbb" "ccc" "ddd") do (
    if "%~1"=="%%~A" (
        set "FLAG=true"
    )
)
if not defined FLAG goto :end
rem // Execution continues here in case a match has been found...

Alternatively, you could do this (using another goto to leave the loop):

for %%A in ("aaa" "bbb" "ccc" "ddd") do (
    if "%~1"=="%%~A" (
        goto :found
    )
)
goto :end
:found
rem // Execution continues here in case a match has been found...

Note that the above code snippets do case-sensitive string comparisons; to change that, use if /I.

Upvotes: 1

Magoo
Magoo

Reputation: 79982

No idea what you're trying to do, but the code you've presented will echo true else goto end if the comparison is true.

if "%env%"==%%A (echo true) else (goto end)

will echo true on a match, otherwise go to end. The positioning of the brackets is critical - ) else ( must be on the same physical line.

Upvotes: 1

Related Questions