T.Kruger
T.Kruger

Reputation: 3

If statement in batch

whatever I insert as docopy, the program always copies files from source to destination. Does anyone know how to fix it? I want to copy files after inserting 'y' and skip it if 'n' is inserted. Of course, I tried if else statement, but it didn't work properly too. After all, program should ask what part of file to rename. I'm sure it's easy for You :)

set source="C:\Users\Desktop\Basic"
set destination="C:\Users\Desktop\CopyofBasic"
set renfiles="C:\Users\Desktop\CopyofBasic"

setlocal EnableDelayedExpansion


set /p docopy="Do You want to copy files? [Y/N]: "

if /i %%docopy%% == "%y%" (
    goto :makecopy
    )
if /i %%docopy%% == "%n%" (
    goto :nagative
    )

:makecopy
    xcopy /s /v /h /k /z %source% %destination%
    goto :renfiles
:negative
    echo None files are copied.
    goto :renfiles

:renfiles
cd %renfiles%
set /p var1="Insert part of filename to replace it: "
set /p var2="Insert new part of filename: "
set /p var3="Insert files fomrat: "

for /r %%G in (%var3%) do (
    set "filename=%%~nxG"
    ren "%%G" "!filename:%var1%=%var2%!"
)

echo Filenames have been already changed.
pause

Upvotes: 0

Views: 58

Answers (2)

CristiFati
CristiFati

Reputation: 41112

There are 2 problems:

  • the conditions are incorrect:

    if /i %%docopy%% == "%y%"
    

    when docopy was having a value of n was evaluating to: if /I %docopy% == "" (goto :makecopy ) which was false so it was skipped. Same thing happened with the next condition, so the next "instruction" in the batch file was the :makecopy label.

  • typo goto:nagative (nAgative)

How the conditions should look like: use " (or [,]) as variable guards, but not %):

if /i "%docopy%" == "y" (
    goto :makecopy
    )
if /i "%docopy%" == "n" (
    goto :negative
    )

@Edit1: Corrected the condition evaluation as @aschipfl noticed.

Upvotes: 1

tjleigh
tjleigh

Reputation: 1144

Consider using choice and testing the errorlevel instead of set /p

http://ss64.com/nt/choice.html

CHOICE /M Do you want to copy files? [Y/N] 
IF errorlevel 2 goto nagative
IF errorlevel 1 goto makecopy

Upvotes: 0

Related Questions