Reputation: 321
Hi I am working on a windows batch file and am trying to get the program to end if the user does not enter a string, but when I run it and do not input anything the whole thing still runs. Any advice would be great thanks.
:: 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
Upvotes: 1
Views: 1814
Reputation: 70971
set /p studentName=Enter student name: || goto :end
With command extensions enabled (the default configuration, or can be enabled with setlocal enableextensions
) the conditional operator ||
(execute next command if the previous failed) will catch the failure (no input) of the set
command to retrieve data.
Upvotes: 1
Reputation: 14370
When variables are set in a normal batch script, they persist in the environment until they are deleted or the environment is closed. Your problem stems from the fact that you gave %studentName%
a value without preparing the environment first. You have two options:
@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
Pros:
Cons:
@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
Pros:
Cons:
Upvotes: 2