1

I have this code:

if "%2"=="32" (
set bit=This is 32bit
)
if "%2"=="64" (
set bit=This is 64bit
)
echo %bit%
)

When I tried using sample.bat /s 64 the output is "This is 64bit", but when I tried using sample.bat /s 32 the output is still "This is 64bit". Then I switch it back to sample.bat 64 the ouput became "This is 32bit". I think the variable initialization is being delayed. Does someone know a workaround?

1 Answer 1

3

If you run sample.bat 64, the 64 is in %1, not %2. The first parameter passed to the batch file is always %1 - the name of the batch file itself is in %0. You're getting some random output remnant or something left over from another attempt. Try this:

setlocal
if "%1"=="32" (
set bit=This is 32bit
)
if "%1"=="64" (
set bit=This is 64bit
)
echo %bit%
)
endlocal

setlocal makes sure that any environmental changes are discarded when your batch file ends, so you don't have to worry about getting leftovers from testing.

This still won't work properly if you just type sample.bat, because you haven't dealt with no parameters at all being passed.

Sign up to request clarification or add additional context in comments.

5 Comments

+1 - Nice catch. I'm embarrassed to say that issue blew right past me without me picking up on it.
I tried your code and it worked.. Thanks! However, it should be evaluated in the second parameter. When I added "if first parameter is /s then go to second parameter and evaluate it if it's a 32 or 64 bit", the value seems stuck always at 32 bit. Can you please check my code in the answers below because I can't post it here in comments section..
It seems that I cannot post it in answers unless it's really an answer, I'll just put it here. NEW CODE: setlocal if "%1"=="/i" ( if "%2"=="32" ( set bit=This is 32bit ) if "%2"=="64" ( set bit=This is 64bit ) echo %bit% endlocal ) The output is now stuck at "This is 32bit" regarding how many times I enter 64
I tried echoing the parameter inside the if statements. I've found out that the culprit is the parameter not being passed in the variable. Does setlocal have something to do with this?
I'm don't understand the problem. What does "parameter not being passed in the variable" mean? And if you want to test the effects of setlocal, just comment both that line and the endlocal one out (just place :: at the beginning of each line).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.