1

Ok i got this basic IF-statement. I want to set a user role, based on it's username. It does look like though, that the set statement never gets executed and therefore i got an empty echo.

if "%username%" == "admin" (
    set role = "admin"
) else (
    set role = "user"
)

echo %role%

Did I miss something or may it be that Windows just does not support that?

1 Answer 1

1

Remove the spaces. You are now setting a value to the environment variable role (with a trailing space that Stack Overflow won't show). Also, the role becomes "admin" (including quotes and a leading space, that is, again, not visible here).

You can verify this by running set without parameters from the command line. It will give you a list of all variables, in which you can clearly see the undesired spaces.

if "%username%" == "admin" (
    set role=admin
) else (
    set role=user
)

echo %role%

The only reason you still need quotes with an if statement, is that the statement would become invalid if %username% didn't exist/was empty. In that case, the line would become:

if == admin (

... Which is of course invalid. It doesn't even need to be quotes, you could also write:

if %username%XYZ == adminXYZ (
Sign up to request clarification or add additional context in comments.

Comments

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.