1

I am using SET in cmd to set a new environment variable, and immediately use it afterwards for comparison. The user is prompted to input a string, and afterwards it should check if the input matches another string (basically a password).

set /P pwd=pwd: & if %pwd%==pwd (echo yes) else (echo no)

The problem I'm having is that it appears that the variable is not set, because no matter if I input the password or not, it always returns me No.

I have also tried separating both commands in a .bat file, but it wouldn't work either.

Hamperfait
  • 465
  • 1
  • 6
  • 18
  • 1
    Why don't you use multiple lines, then it works. Btw. You should enclose your variable in the `IF` `IF "%pwd%"=="pwd"` to avoid syntax errors, when `%pwd%` is empty – jeb Apr 08 '19 at 06:15
  • For use in CMD: `cmd /v:on /c set /p pwd=pwd: ^&^& if !pwd!==pwd (echo yes) else (echo no)`. 1 line uses `cmd /v:on` to execute `cmd` with Delayed Expansion enabled and after `/c` is the command line to execute by `cmd`. The `&` are escaped with `^` so are not used by the current process, instead by the new instance of `cmd`. – michael_heath Apr 08 '19 at 09:08

1 Answers1

2

Your code doesn't work because it's on one line. See set /?, setlocal /?, for /? and cmd /? to see a discussion on delayed expansion.

CMD processes batch files line by line and fills in all %var% when it reads the line. This is how MSDos worked and CMD needs to be compatable. Delayed expansion the variables are expanded when they are used not when read. As !var! is a legal MSDos name (as in %!var!%) you must optin to new behaviour (new in 1993 anyway).

Noodles
  • 264
  • 2
  • 3
  • @Hamperfait Did you read `cmd /?`, there it's explained. `Delayed expansion the variables are expanded when they are used not when read` – jeb Apr 08 '19 at 06:45
  • 1
    Why would *on one line* be important in a batch file? You can press enter instead of `&` (ps use `&&` in future). – Noodles Apr 08 '19 at 06:47
  • To use the variable in the same (logical) line, you need [delayed expansion](https://stackoverflow.com/a/30284028/2152082) – Stephan Apr 08 '19 at 08:38
  • @noodles The thing is I am trying to reduce the amount of stuff I have to write to disk and would prefer not to use batch files, although they do work. That is why it would be better to run the command on one line, but if it does not work then a batch it is. – Hamperfait Apr 08 '19 at 10:03
  • You don't write anymore to disk. `cmd /v:on /c "set /P pwd=pwd:&if !pwd!==pwd (echo yes) else (echo no)"`. Sounds like you are voodoo programming. – Noodles Apr 08 '19 at 10:22