Batch variables
From wikinotes
Variable Scope
REM a regular variable %VAR% REM if variable is from different scope !VAR!
Assign Variable
REM assign a variable set VAR=value set VAR=value with spaces REM file contents as variable set /p VAR < file.txt REM result of command as variable echo "hi" > tempfile.txt set /p VAR < tempfile.txt DEL tempfile.txt REM request user input for variable set /p VAR=
User Input
set /p REPLY=Please Enter Y/N
Math
REM test+=1 set /a test=%test%+1
Delayed Expansion
When the set command is used to set a variable within the scope of a ( and ), it is not parsed until the ( and ) are finished. (So the variable does not contain a value until the scope ends). To get around this, anywhere in your script add:
setlocal enabledelayedexpansionand then when you want to echo or test your variable within that scope instead of using the syntax
echo %variable%use the syntax
echo !variable!
Last N chars of Variable
@setlocal enableextensions enabledelayedexpansion @echo off set variable=bg layer echo !variable! if "x!variable:~-1!"=="xs" ( echo variable is plural ) else ( echo variable is not plural ) pause
Strip Quotes from Variable
echo %~1