kzaiwo
kzaiwo

Reputation: 1768

Batch Scripting - IF statement not working if SET is called inside another IF

Here is my code:

@echo off
setlocal EnableDelayedExpansion

IF EXIST "sample.txt" (
    set /p RETRY="Need to re-download file. Proceed (y/n)? "

    echo RETRY is !RETRY!
    if !RETRY!=="y" (
        echo Retrying download now
    ) else (
        echo Retry rejected
    )
) else (
    echo File does not exist
)

pause

Basically, I have an IF condition and inside it, I need to get a user input and check its value with another IF statement.

Problem is - variable has been updated and it prints correctly but for some reason, it is being evaluated incorrectly inside the nested IF. Help?

Actual output:

Need to re-download file. Proceed (y/n)? y
RETRY is y
Retry rejected
Press any key to continue . . .

Expected:

Need to re-download file. Proceed (y/n)? y
RETRY is y
Retrying download now
Press any key to continue . . .

Upvotes: 0

Views: 47

Answers (1)

user7818749
user7818749

Reputation:

You did not double quote both sides of the comparison:

if /I "!RETRY!"=="y"

I would however replace that entire piece of code to use choice instead:

@echo off
setlocal enabledelayedexpansion

if not exist "sample.txt" echo File does not exist & goto :end
choice /c YN /m "Need to re-download file Proceed"
if %errorlevel% equ 1 (
    echo retrying download now
) else (
    echo Retry rejected
)
:end
pause

Upvotes: 1

Related Questions