Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining and using a variable in batch file

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?

like image 702
Jamie Dixon Avatar asked May 11 '12 13:05

Jamie Dixon


People also ask

How do I echo a variable in a batch file?

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.

How do I set the global variable in a batch file?

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.

What does && do in batch file?

&& 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 ).


2 Answers

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.

like image 159
Brian Nixon Avatar answered Sep 16 '22 14:09

Brian Nixon


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.

like image 38
dbenham Avatar answered Sep 17 '22 14:09

dbenham