Following code could be used to check input of user:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
:setmyvar
set "myvariable=""
set /P "myvariable=Please enter: "
set "TestVar=!myvariable:"=!"
if not defined TestVar goto setmyvar
if not "!TestVar!" == "!myvariable!" (
echo/
echo Variable cannot contain quotation marks.
echo/
pause
echo/
goto setmyvar
)
echo Success^^!
rem Other commands.
endlocal
Before prompting the user the environment variable myvariable
is defined with a double quote. In case of user just hits RETURN or ENTER the environment variable myvariable
keeps its current value (or is still not defined if not defined before).
After user prompt a new environment variable TestVar
is defined with value of environment variable myvariable
, but with all double quotes removed.
There are now three possibilities:
TestVar
is not defined at all now as the user did not enter anything or just double quotes.
TestVar
is different to myvariable
as myvariable
contains among other characters also 1 or more double quotes.
TestVar
is equal myvariable
as the user entered a string which does not contain any double quote.
It is necessary for the comparison of not equal environment variables to use delayed expansion as otherwise with immediate environment variable expansion %myvariable%
with double quotes would result in a syntax error.
In first case the user is simply prompted once again.
In second case the user is informed about the requirement to enter the string without quotation marks and then can enter the string once again whereby the user can use the UP ARROW to recall previous entered string and edit it.
And in third case the batch file execution continues.
The exclamation mark in text to output with echo
must be escaped with two carets because of delayed expansion is still enabled as needed for the remaining code to access value of myvariable
. After endlocal
the environment variable myvariable
does not exist anymore except the following command line is used:
endlocal & set "myvariable=%myvariable%"
This line would define myvariable
in previous environment restored by command endlocal
with current value of myvariable
in active environment on parsing this command line.
echo/
just outputs a blank line in a more safer way than echo.
does.
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.
echo /?
endlocal /?
goto /?
if /?
rem /?
set /?
setlocal /?
For more help on what setlocal
and endlocal
do read this answer and the two other answers referenced there. For an explanation on using set "variable=value"
see the answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line?