0

Today is my first time creating a .bat file and I'm finding some odd (for me) problem. Maybe is something basic but as per now I wasn't able to get an answer about why this is happening.

@echo off

:SETPATH
set "installpath="
set /p installpath="Enter path for the installation. Leaving this empty will install this here %CD% "

if not defined installpath set "installpath=%CD%"

if not exist %installpath% (
    :CONFIRM
    set /P c=Create %installpath% directory [Y/N] ?
    if /I "%c%" == "Y" (
        md %installpath%
        GOTO :INSTALL
    )
    if /I "%c%" == "N" goto :SETPATH
    GOTO :CONFIRM
)

:INSTALL

:: Here goes install proccess
pause

This is simple, as you can see, user needs to prompt a directory where something will be installed later, and in case it doesn't exists, it needs to be created. If the user leaves the input empty, then the thing I want to install installs in the current directory.

When I run the .bat file, I got asked twice to input: Create %installpath% directory [Y/N] ?

The second time I set Y or N, then it continues on.

Can anyone give me light at why this is happening and how to solve it? Thank you!

Kyrade
  • 1
  • Why write a new batch file? You should use PowerShell instead. – Bill_Stewart Jan 26 '17 at 18:33
  • I've been asked to provide a .bat file that prepares some website to be checked (The main thing is the website). So basically, that is why I'm creating it. – Kyrade Jan 26 '17 at 18:38
  • PowerShell can also run scripts and is much more powerful than cmd.exe. – Bill_Stewart Jan 26 '17 at 18:40
  • You need [delayed expansion](http://ss64.com/nt/delayedexpansion.html) for variable `c` as you are writing *and* reading it within the same (parenthesised) block of code... – aschipfl Jan 26 '17 at 18:46
  • Thank you both, with these two answers I learned something new, and it works. Thanks again :) (I did see that question, aschipfl, but at that moment didn't see the relation, thanks!). – Kyrade Jan 26 '17 at 19:15
  • 1
    There is one more thing I'd like to point out. It's not good to declare and `goto` labels inside an IF-block. It doesn't really matter for your code (if you'd add an ELSE-branch it will though) but the `goto` "destroys" `IF` and `FOR` blocks. I would advise you to use the `choice` command for yes/no input (no delayed expansion needed and handles input validation). Take a look to [this answer](http://stackoverflow.com/a/41622919) , it will give some clearance on how `goto` breaks contexts and on the `choice` command. – J.Baoby Jan 26 '17 at 20:15
  • 1
    [**Never** use `:label` nor `:: label-like comment` inside a command block enclosed in `()` parentheses](http://stackoverflow.com/a/32147995/3439404)! – JosefZ Jan 26 '17 at 23:39
  • 1
    Ok, I changed the goto, now using a Choice instead. Thank you for the help! – Kyrade Jan 27 '17 at 10:04

0 Answers0