Declaring and using a variable in Windows batch file (.BAT)
I'm trying to declare and use a variable in my batch file. It looks like it should be simple.
@ECHO OFF
SET location = "bob"
ECHO We're working with "%location%"
The output I get is:
We're working with ""
What's going on here? Why is my variable not being echo'd?
The space before the =
is interpreted as part of the name, and the space after it (as well as the quotation marks) are interpreted as part of the value. So the variable you've created can be referenced with %location %
. If that's not what you want, remove the extra space(s) in the definition.
The spaces are significant. You created a variable named (enclosing single quotes added to show location of space) 'location '
with a value of ' "bob"'
.
If you want quotes in your value, then your code should look like
set location="bob"
If you don't want quotes, then your code should look like
set location=bob
Or better yet
set "location=bob"
The last syntax prevents inadvertent spaces from getting in the value, and also protects against special characters like & | etc.
input location.bat
@echo off
cls
set /p "location"="bob"
echo We're working with %location%
pause
output
We're working with bob
(mistakes u done : space
and " "
)