简体   繁体   中英

If syntax in windows batch

I'm trying to make this work in a windows batch file:

if not exist "%~n1.ext" (
    set /P z="PROMPT (y,n)?"
            if /i "%z%" == "y" (
                echo if is working
            )
) 

But no matter what the input is, it never goes into the echo part. Is there something wrong in the syntax?

When you use a variable inside a block (between ( and ) , you need to enable delayed expansion:

setlocal enabledelayedexpansion
set var=hello
if "a"=="a" (
  set var=world
  echo %var% !var!
)

Stephan is correct, you need to use enabledlayedexpansion when using a nested variable. Here's your code with that syntax (replacing % with ! when using such variables):

setlocal enabledelayedexpansion
if not exist "%~n1.ext" (
    set /P z="PROMPT (y,n)?"

    if /i "!z!" == "y" (
        echo if is working
    )
) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM