Windows 배치 파일에서 어떻게 "확실합니까?"프롬프트를 만들 수 있습니까?
한 곳에서 다른 곳으로 여러 파일을 자동으로 복사하는 배치 파일이 있습니다. 유일한 것은 명령 버퍼에서 해당 명령을 실수로 계속 선택하고 커밋되지 않은 변경 사항을 대량 덮어 쓰는 데 도움이되는 것뿐입니다.
.bat 파일이 "확실합니까"라고 표시하고 나머지 파일을 실행하기 전에 "y"를 입력하도록하려면 어떤 코드가 필요합니까? "y"만 입력하면 해당 행에서 실행을 종료해야합니다.
수정 11 월 27 일 확인 아직 알아낼 수 없기 때문에 답변이없는 것으로 표시했습니다. 내가 "exit"라고 부를 때; 내가 원하는 것이 아닌 cmd.exe를 닫습니다. 이 모든 것은 Windows가 명령 버퍼를 잘못 구현했기 때문입니다. [적어도 익숙한 것과는 다릅니다]
다음과 같은 것을 원합니다.
@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
은 try CHOICE 명령을 , 예를 들어,
CHOICE /C YNC /M "Press Y for Yes, N for No or C for Cancel."
이 choice
명령은 모든 곳에서 사용할 수 없습니다. 최신 Windows 버전에서는 set
명령에 /p
사용자 입력을받을 수 있는 옵션이 있습니다.
SET /P variable=[promptString]
자세한 내용 set /?
은 참조
Windows 명령 줄에서 사용자 프롬프트에 사용할 수있는 두 가지 명령이 있습니다.
- 설정 옵션을
/P
사용할 수 명령 확장으로 모든 Windows NT 버전에서 사용 가능 하고 - choice.exe 는 기본적으로 Windows Vista 이상 PC 사용자 용 Windows 버전과 Windows Server 2003 이상 Windows 서버 버전에서 사용할 수 있습니다.
set 는 Windows 명령 프로세서의 내부 명령입니다 cmd.exe
. /P
사용자에게 문자열을 묻는 옵션 은 기본적으로 활성화 된 활성화 된 명령 확장에서만 사용할 수 있습니다. 그렇지 않으면 요즘에는 배치 파일이 거의 작동하지 않습니다.
choice.exe 는에있는 별도의 콘솔 응용 프로그램 (외부 명령)입니다 %SystemRoot%\System32
. Windows XP에서는 기본적으로 사용할 수 없지만 Windows Server 2003에서는 기본적으로 사용할 수있는 다른 많은 명령처럼 Windows XP에서 choice.exe
사용할 수 있도록 Windows Server 2003의 디렉터리 %SystemRoot%\System32
를 Windows XP 시스템의 디렉터리 에 복사 할 수 있습니다 .
그것은 찬성 사용하는 것이 좋습니다 CHOICE 의 사용을 통해 SET / P 다음과 같은 이유로 인해 :
- CHOICE 는 옵션 (및 ) 뒤에 지정된 키 (각각 STDIN 에서 읽은 문자) 만 허용 하고 사용자가 잘못된 키를 누르면 오류 경고음을 출력합니다.
/C
Ctrl+C - CHOICE 는 허용되는 키 중 하나가 아닌 다른 키를 누를 필요가 없습니다. CHOICE 는 허용 가능한 키를 누르면 즉시 종료되며 SET / P 는 사용자가 RETURN또는로 입력을 완료해야합니다 ENTER.
- 함께 것이 가능하다 CHOICE가 자동으로 사용자를 기다리지 않고 몇 초 후 기본 옵션을 계속하려면 기본 옵션 및 시간 제한을 정의 할 수 있습니다.
- 출력은
echo Y | call PromptExample.bat
on using CHOICE 와 같은 것을 사용하여 프롬프트가있는 배치 파일을 호출하는 다른 배치 파일에서 자동으로 프롬프트에 응답 할 때 더 좋습니다 . - 사용자의 선택의 평가는 훨씬 쉽게 CHOICE 인해 초이스 에 할당 된 프레스 키 (문자)에 따라 값이 종료 ERRORLEVEL 쉽게 다음 평가 될 수있다.
- SET / P 에서 사용되는 환경 변수 는 사용자가 키만 누르 RETURN거나 ENTER사용자에게 메시지를 표시하기 전에 정의되지 않은 경우 정의되지 않습니다. SET / P 명령 줄 에서 사용 된 환경 변수는 이전에 정의 된 경우 현재 값을 유지하고 사용자는 RETURN또는 ENTER.
- 사용자는 구문 오류 로 인해 나중에 배치 파일 실행을 종료 하거나 배치 파일에 전혀 포함되지 않은 명령을 실행할 때 문자열을 포함하여 SET / P 로 프롬프트 될 때 무엇이든 자유롭게 입력 할 수
cmd
있습니다. 좋은 코딩 된 배치 파일. 실수로 또는 의도적으로 잘못된 사용자 입력으로 SET / P를 보호 하려면 약간의 노력이 필요 합니다.
다음은 Windows를 실행하는 중고 컴퓨터에서 사용할 수없는 기본 선택 및 대신 SET / P 를 사용하는 프롬프트 예 choice.exe
입니다.
@echo off
echo This is an example for prompting a user.
echo/
if exist "%SystemRoot%\System32\choice.exe" goto UseChoice
setlocal EnableExtensions EnableDelayedExpansion
:UseSetPrompt
set "UserChoice=N"
set /P "UserChoice=Are you sure [Y/N]? "
set "UserChoice=!UserChoice: =!"
if /I "!UserChoice!" == "N" endlocal & goto :EOF
if /I not "!UserChoice!" == "Y" goto UseSetPrompt
endlocal
goto Continue
:UseChoice
%SystemRoot%\System32\choice.exe /C YN /N /M "Are you sure [Y/N]? "
if errorlevel 2 goto :EOF
:Continue
echo So your are sure. Okay, let's go ...
참고 : 이 배치 파일은 명령 인터프리터 command.com
대신 사용하여 Windows 95 / 98 / ME에서 사용할 수없는 명령 확장을 사용 합니다 cmd.exe
.
Windows NT4 / 2000 / XP set "UserChoice=!UserChoice: =!"
에서이 배치 파일을 호출 할 수 있도록 명령 줄 이 추가되었으며 . 두 문자열 비교를 실행하기 전에 STDIN 에서 읽은 문자열에서 모든 공백을 삭제합니다 .echo Y | call PromptExample.bat
echo Y| call PromptExample.bat
echo Y | call PromptExample.bat
결과 Y는SPACE 환경 변수에 할당하기 UserChoice
. "Y "
대소 문자를 구분하지 "N"
않거나 "Y"
먼저 모든 공백을 삭제 하지 않기 때문에 프롬프트를 두 번 처리하게됩니다 . 그래서 UserChoice
와 YSPACE 값이 옵션을 사용하여 메시지를 두 번 실행 결과 것처럼 N
두 번째 프롬프트 실행에 배치 파일에서 기본값으로 정의하는 배치 파일 처리의 예상치 못한 종료에서 다음 결과. 예, SET / P 의 안전한 사용 은 정말 까다 롭지 않습니까?
옵션 목록에서 사용자에게 선택하라는 메시지를 표시하기위한 SET / P 및 CHOICE의 사용에 대한 자세한 내용은 Windows 명령 인터프리터가 잘못된 사용자 입력으로 배치 파일 실행을 종료하는 것을 중지하는 방법에 대한 답변을 참조하십시오 .
더 많은 힌트 :
- IF 는 비교 연산자의 왼쪽과 오른쪽 두 문자열을 큰 따옴표 를 포함 하여 비교 합니다. 비교 대소 문자 구분은의 값이 아닙니다 그래서
UserChoice
으로N
하고Y
있지만,의 값UserChoice
에 의해 둘러싸여"
로"N"
하고"Y"
. - The IF comparison operators
EQU
andNEQ
are designed primary for comparing two integers in range -2147483648 to 2147483647 and not for comparing two strings.EQU
andNEQ
work also for strings comparisons, but result on comparing strings in double quotes on a useless attempt to convert left string to an integer.EQU
andNEQ
can be used only with enabled command extensions. The comparison operators for string comparisons are==
andnot ... ==
which work even with disabled command extensions as evencommand.com
of MS-DOS and Windows 95/98/ME already supported them. For more details on IF comparison operators see Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files. - The command
goto :EOF
requires enabled command extensions to really exit batch file processing. For more details see Where does GOTO :EOF return to?
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
choice /?
echo /?
endlocal /?
goto /?
if /?
set /?
setlocal /?
See also:
- This answer for details about the commands SETLOCAL and ENDLOCAL.
- Why is no string output with 'echo %var%' after using 'set var = text' on command line?
It explains the reason for using syntaxset "variable=value"
on assigning a string to an environment variable. - Single line with multiple commands using Windows batch file for details on
if errorlevel X
behavior and operator&
. - Microsoft documentation for using command redirection operators explaining redirection operator
|
and handle STDIN. - Wikipedia article about Windows Environment Variables for an explanation of
SystemRoot
. - DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/
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...
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%==1 goto yes
if %errorlevel%==2 goto no
:yes
echo yes
goto :EOF
:no
echo no
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.
'development' 카테고리의 다른 글
Node.js를 사용한 웹 사이트 구축 모범 사례 (0) | 2020.10.09 |
---|---|
Gradle Build Android 프로젝트 '모든 종속성을 해결할 수 없음'오류 (0) | 2020.10.09 |
바이너리 프로토콜 대 텍스트 프로토콜 (0) | 2020.10.09 |
Android는 sd 카드 폴더에 쓰기 (0) | 2020.10.09 |
Font Awesome에서 SVG 추출 (0) | 2020.10.09 |