loading

Batch/.bat input & output?

I want to make a batch program where I can ask an if statement but there would only be a possibility of two responses. For example if I made the batch file asked "Did you have a good day?", I would only want the user to be able to answer y or n.

thegeeke5 years ago
The set /p and if command work well. The only problem is that if you are used to any other type of language, you are used to using if then else. With batch you just get if, and then is implied, so it will not be the correct syntax if you use it. Anyway, the program you described is listed below:

@echo off
title "My title here"
:start
echo Did you have a nice day?
set /p "com=Y or N: "
if %com%==y goto yes
if %com%==n goto no
if %com%==Y goto yes
if %com%==N goto no
echo I'm sorry, you must answer y or n.
goto start
:yes
rem your yes code here

:no
rem your no code here

exit
To cut down on the amount of repeating line (if %com%==Y... etc) you can use the /I switch for the IF command.

This allows two strings to be compared case-insensitively, making it easier. Remember, delayed expansion needs to be on.

setlocal enabledelayedexpansion
set /p question=Question here (Possible answers):
if /I %question%==answer echo %question% was entered
And, because the reply button is still not showing itself on thegeeke's comment, I will have to write it here:

There is "IF" and "ELSE" command in batch, they're just not used like in most "proper" scripting languages...
AndyGadget5 years ago
 
You want the 'CHOICE' command (choice.com) which was an external executable part of MSDOS for versions up to Win98 but was dropped with XP.  However it is still available in the supplemental pack, downloadable from HERE.  

Example :
@ECHO off
@CHOICE /C:123
IF ERRORLEVEL 3 GOTO three
IF ERRORLEVEL 2 GOTO two
IF ERRORLEVEL 1 GOTO one
GOTO end
:one
ECHO You have pressed "1"!
GOTO end
:two
ECHO You have pressed "2"!
GOTO end
:three
ECHO You have pressed "3"!
:end
@PAUSE