Batch file 如果用户未输入任何内容,如何结束批处理文件
嗨,我正在处理一个windows批处理文件,如果用户没有输入字符串,我会尝试让程序结束,但是当我运行它并且没有输入任何内容时,整个程序仍然运行。任何建议都很好,谢谢Batch file 如果用户未输入任何内容,如何结束批处理文件,batch-file,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%
:: 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
在正常批处理脚本中设置变量时,变量将一直保留在环境中,直到删除或关闭环境。您的问题源于这样一个事实,即您没有首先准备环境就给了
%studentName%
一个值。您有两个选择:
选项1:在使用变量之前清除它
优点:
- 如果需要保存其他变量,可以反复运行,直到命令提示符关闭为止
- 如果有很多变量不需要持久化,则需要手动清除每个变量
选项2:使用setlocal创建新环境 优点:
- 如果有很多变量需要清除,这将节省大量的键入工作
- 如果需要使用时,无论如何都需要使用此方法
- 除非将变量值存储在某个位置,否则变量值不会在多个运行中保持不变
set/p studentName=输入学生姓名:| |转到:结束
启用命令扩展(默认配置,或可通过
setlocal enableextensions
启用)时,条件运算符|
(如果上一个命令失败,则执行下一个命令)将捕获set
命令的失败(无输入)以检索数据。我相信您会用括号替换引号,ie:如果“%studentname%”==[]转到结束
让我猜一下:您先用名称测试了脚本,然后没有名称,并且在测试之间从未关闭命令提示符,对吗?@TaylorAckley-甚至一点都不正确。对if
语句使用引号被认为是最佳做法。此外,由于引号和括号都被视为比较字符串的一部分,因此您发布的语句在任何情况下都不会是真的。哦,天哪。。不,我没有在两次测试之间结束。谢谢你,黑暗的东西
@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
@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