I'm trying to define and use a variable in a 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 the following:
We're working with ""
What's going on here? Why is my variable not being echo'd?
Please open a command prompt window, run set /? and read the output help. The syntax is set /P variable=prompt text or better set /P "password=Enter your password: " . And please note that variable password keeps its current value if already defined and user hits just RETURN or ENTER.
Variable Scope (Global vs Local) In the batch script, we can create a local variable using the SETLOCAL command. The scope of the local variable only between the SETLOCAL and ENDLOCAL command and it is destroyed as soon as the ENDLOCAL statement is executed.
&& runs the second command on the line when the first command comes back successfully (i.e. errorlevel == 0 ). The opposite of && is || , which runs the second command when the first command is unsuccessful (i.e. errorlevel != 0 ).
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 'location '
with a value of' "bob"'
. Note - enclosing single quotes were added to show location of space.
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 trailing spaces from getting in the value, and also protects against special characters like &
|
etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With