如果用户什么都不输入,如何结束批处理文件

时间:2017-03-22 23:37:06

标签: batch-file

您好我正在处理Windows批处理文件,如果用户没有输入字符串,我试图让程序结束,但是当我运行它并且不输入任何东西时,整个事情仍然运行。任何建议都会非常感谢。

:: Sets variable studentName to what the user inputs.
set /p studentName=Enter student name: 

::If the user does not input anything go to end option
if "%studentName%"=="" goto end

:: Displays filename, student's entered name, and the random number
echo Usage: %0 %studentName%
echo Hello %studentName%, your secret number is %RANDOM%

:: Pauses screen while user reads secret number
pause

:: Clear screen for user.
cls

echo Hope you remeber that number, %studentName%!


:end
echo Usage: %0 studentName
pause
exit /b

2 个答案:

答案 0 :(得分:2)

在常规批处理脚本中设置变量时,它们会一直存在于环境中,直到删除它们或关闭环境为止。您的问题源于这样一个事实,即您在没有首先准备环境的情况下给了%studentName%一个值。您有两种选择:

选项1:在使用之前清除变量

@echo off

:: Clears the value of %studentName%. The quotes are to prevent extra spaces from sneaking onto the end
set "studentName="

:: Sets variable studentName to what the user inputs.
set /p studentName=Enter student name: 

::If the user does not input anything go to end option
if "%studentName%"=="" goto end

:: Displays filename, student's entered name, and the random number
echo Usage: %0 %studentName%
echo Hello %studentName%, your secret number is %RANDOM%

:: Pauses screen while user reads secret number
pause

:: Clear screen for user.
cls

echo Hope you remeber that number, %studentName%!


:end
echo Usage: %0 studentName
pause
exit /b

优点:

  • 如果您需要保留其他变量,可以一遍又一遍地运行它们,它们将一直保持到命令提示符关闭为止。

缺点:

  • 如果您有很多需要的变量,则需要手动清除每个变量。

选项2:使用setlocal创建新环境

@echo off
setlocal

:: Sets variable studentName to what the user inputs.
set /p studentName=Enter student name: 

::If the user does not input anything go to end option
if "%studentName%"=="" goto end

:: Displays filename, student's entered name, and the random number
echo Usage: %0 %studentName%
echo Hello %studentName%, your secret number is %RANDOM%

:: Pauses screen while user reads secret number
pause

:: Clear screen for user.
cls

echo Hope you remeber that number, %studentName%!


:end
echo Usage: %0 studentName
pause
exit /b

优点:

  • 如果要清除很多变量,这将节省大量的输入。
  • 如果当您需要使用delayed expansion时,无论如何都需要使用此方法

缺点:

  • 除非您将变量值存储在某个位置,否则变量值不会在多次运行中持续存在

答案 1 :(得分:1)

set /p studentName=Enter student name: || goto :end

启用命令扩展(默认配置,或者可以使用setlocal enableextensions启用)条件运算符||(如果先前失败,则执行下一个命令)将捕获失败(无输入)set命令来检索数据。

相关问题