1

I have a .bat file that would ask your name and save it in a .txt file. If the file already exists, I want it to say "Your Name is ____"

@echo off
if exist BatchfileOutput.txt (
cls
FOR /F %%i IN (BatchfileOutput.txt) DO echo Your name is %%i

) else (
echo What is your name?
set /p %name%= )
echo %name% > BatchfileOutput.txt

pause

It prints ECHO is off, probably due to @echo off at the top. If I manually add text to the file, it displays the text. Could anyone help me get around this?

JRG
  • 4,037
  • 3
  • 23
  • 34
  • 1
    Possible duplicate of [Windows Batch Variables Won't Set](https://stackoverflow.com/questions/9681863/windows-batch-variables-wont-set) – SomethingDark Jul 12 '17 at 00:08

2 Answers2

1

You need

set /p name= 

not

set /p %name%= 

which would set the variable named the current contents of NAME

Magoo
  • 77,302
  • 8
  • 62
  • 84
0
  1. It is set /P name= but not set /P %name%=.

  2. The command echo %name% needs to be moved into the else block too. For this to work, delayed expansion must be established:

    @echo off
    if exist "BatchfileOutput.txt" (
        cls
        for /F "usebackq tokens=*" %%i in ("BatchfileOutput.txt") do echo Your name is %%i
    ) else (
        echo What is your name?
        set /P name=
        setlocal EnableDelayedExpansion
        > "BatchfileOutput.txt" echo !name!
        endlocal
    )
    pause
    

    I moved the redirection part to the front in order to avoid a trailing SPACE to be output also.

    To avoid delayed expansion, you could avoid the parenthesised else block by using goto :Label as the last command of the if block, then omitting else and the parentheses, and then placing :Label before pause:

    @echo off
    if exist "BatchfileOutput.txt" (
        cls
        for /F "usebackq tokens=*" %%i in ("BatchfileOutput.txt") do echo Your name is %%i
        goto :Label
    )
    echo What is your name?
    set /P name=
    > "BatchfileOutput.txt" echo %name%
    :Label
    pause
    

I quoted all file paths and therefore used the usebackq option of for /F in order to avoid trouble with such strings containing white-spaces. Furthermore, I stated the tokens=* option for the for /F loop to read the full line even in case the name consists of multiple words.

aschipfl
  • 33,626
  • 12
  • 54
  • 99