How can I make an “are you sure” prompt in a Windo

2019-03-08 17:18发布

I have a batch file that automates copying a bunch of files from one place to the other and back for me. Only thing is as much as it helps me I keep accidentally selecting that command off my command buffer and mass overwriting uncommited changes.

What code would I need for my .bat file to make it say "are you sure", and make me type "y" before it ran the rest of the file? If anything but "y" is typed it should exit execution on that line.

Edit Nov 27 Ok I marked this unanswered again because I still can't figure it out. When I call "exit;" it closes cmd.exe which is not what I want. All this because Windows implemented command buffer wrong [differently than what I am used to at least]

7条回答
forever°为你锁心
2楼-- · 2019-03-08 17:36

try the CHOICE command, e.g.

CHOICE /C YNC /M "Press Y for Yes, N for No or C for Cancel."
查看更多
We Are One
3楼-- · 2019-03-08 17:42

If you want to the batch program to exit back to the prompt and not close the prompt (A.K.A cmd.exe) you can use "exit /b".

This may help.

set /p _sure="Are you sure?"
::The underscore is used to ensure that "sure" is not an enviroment
::varible
if /I NOT "_sure"=="y" (
::the /I makes it so you can
exit /b
) else (
::Any other modifications...
)

Or if you don't want to use as many lines...

Set /p _sure="Are you sure?"
if /I NOT "_sure"=="y" exit /b
::Any other modifications and commands.

Hope this helps...

查看更多
小情绪 Triste *
4楼-- · 2019-03-08 17:43

Here is a simple example which I use in a backup (.bat / batch) script on Windows 10, which allows me to have different options when making backups.

...

:choice
set /P c=Do you want to rsync the archives to someHost[Y/N]?
if /I "%c%" EQU "Y" goto :syncthefiles
if /I "%c%" EQU "N" goto :doonotsyncthefiles
goto :choice

:syncthefiles
echo rsync files to somewhere ...
bash -c "rsync -vaz /mnt/d/Archive/Backup/ user@host:/home/user/Backup/blabla/"
echo done

:doonotsyncthefiles
echo Backup Complete!

...

You can have as many as you need of these blocks.

查看更多
地球回转人心会变
5楼-- · 2019-03-08 17:44

You want something like:

@echo off
setlocal
:PROMPT
SET /P AREYOUSURE=Are you sure (Y/[N])?
IF /I "%AREYOUSURE%" NEQ "Y" GOTO END

echo ... rest of file ...


:END
endlocal
查看更多
混吃等死
6楼-- · 2019-03-08 17:47

Here a bit easier:

@echo off
set /p var=Are You Sure?[Y/N]: 
if %var%== Y goto ...
if not %var%== Y exit

or

@echo off
echo Are You Sure?[Y/N]
choice /c YN
if %errorlevel%== Y goto ...
if %errorlevel%== N exit
查看更多
Animai°情兽
7楼-- · 2019-03-08 17:50

The choice command is not available everywhere. With newer Windows versions, the set command has the /p option you can get user input

SET /P variable=[promptString]

see set /? for more info

查看更多
登录 后发表回答