Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yes/no batch file

Tags:

batch-file

In my batch file I want to ask the user a question.

I wrote the following:

SET /P ANSWER=Click Y to continue or N to stop (Y/N)

but I get the message without the last ).

Someone know why?

Thanks!

like image 981
zipi Avatar asked Dec 17 '12 13:12

zipi


People also ask

How do you ask yes or no in CMD?

Pipe the echo [y|n] to the commands in Windows PowerShell or CMD that ask “Yes/No” questions, to answer them automatically.

Are you sure y/n CMD?

The del command displays the following prompt: Are you sure (Y/N)? To delete all of the files in the current directory, press Y and then press ENTER. To cancel the deletion, press N and then press ENTER.

What does 0 |% 0 Do in batch?

What it is: %0|%0 is a fork bomb. It will spawn another process using a pipe | which runs a copy of the same program asynchronously. This hogs the CPU and memory, slowing down the system to a near-halt (or even crash the system).


1 Answers

Because you're using that prompt within a parenthesised block, e.g.

if ... (
  ...
  set /P ANSWER=Blah (Y/N)
)

or

for %%x in (...) do (
  ...
  set /P ANSWER=Blah (Y/N)
)

You have to escape the closing parenthesis in that case:

SET /P ANSWER=Click Y to continue or N to stop (Y/N^)

or quote the whole argument:

SET /P "ANSWER=Click Y to continue or N to stop (Y/N)"

otherwise it closes the block. And if you had anything after that closing parenthesis you'd get a syntax error.

An easier method of what you do there would probably be the choice command:

choice /M "Press Y to continue or N to stop" /c YN

You can then check the errorlevel afterwards to find out the user's choice:

if errorlevel 255 (
  echo Error
) else if errorlevel 2 (
  echo No.
) else if errorlevel 1 (
  echo Yes.
) else if errorlevel 0 (
  echo Ctrl+C pressed.
)
like image 92
Joey Avatar answered Nov 10 '22 07:11

Joey