Declaration
To create a simple variable and assign it to a value or string use the SET
command:
Reading of files in a Batch Script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. Since there is a no direct command to read text from a file into a variable, the ‘for’ loop needs to be used to serve this purpose. Let’s look at an example on how this can be achieved. Read file contents into a variable: for /f 'delims='%%x in (version.txt) do set Build=%%x. Set /p Build=line in the file, for more lines the for variant will put the last line into the variable, while set /p will use the first.
Here, the code declares a new variable var
with a value of 10
. By default all variables are stored internally as strings; this means that the value 10
is no different to foo1234
or Hello, World!
Notes about quotation marks
I'm writing a batch file that needs to read In a text file with multiple lines (2-3 or more) and assign them to variables (i.e. Line1, Line2, Line3). Which will then act on those to run jobs based on the variables read in. What is the easiest way to do this preferably without for loops or delims. I have a batch file that I would like to read in each line and set each line to a variable. For example my batch file is as follows: set /p hostname=variables.txt set /p backupdrive=variables.txt set /p backupdir=variables.txt set /p xbackupdir=variables.txt This does not work because it is only reading in the first line each time, so each.
Quotation marks used will be included in the variable's value:
Spaces in variables
Batch language considers spaces to be acceptable parts of variable names. For instance, set var = 10
will result in a variable called var
that contains the value 10
(note the extra space to the right of var and the left of the 10).
Using quotation marks to eliminate spaces
In order to prevent spaces, use quotation marks around the entire assignment; the variable name and value. This also prevents accidental trailing spaces at the end of the line (the ␣
character denotes a space):
Also, use quotation marks when joining multiple statements with &
or |
- alternatively, put the symbol directly after the end of the variable's value:
Usage
This code will echo the value of var
If setLocal EnableDelayedExpansion
is used, the following will echo the value of var
(the standard expression %var% will not work in that context).
In batch files, variables can be used in any context, including as parts of commands or parts of other variables. You may not call a variable prior to defining it.
Using variables as commands:
Using variables in other variables:
Variable Substitution
Unlike other programming languages, in a batch file a variable is substituted by its actual value before the batch script is run. In other words, the substitution is made when the script is read into memory by the command processor, not when the script is later run.
This enables the use of variables as commands within the script, and as part of other variable names in the script, etc. The 'script' in this context being a line - or block - of code, surrounded by round brackets: ()
.
But this behaviour does mean that you cannot change a variable's value inside a block!
will print
since (as you see, when watching the script run in the command window) it is evaluated to:
In the above example, the ECHO
command is evaluated as Hello
when the script is read into memory, so the script will echo Hello
forever, however many passes are made through the script.
The way to achieve the more 'traditional' variable behaviour (of the variable being expanded whilst the script is running) is to enable 'delayed expansion'. This involves adding that command into the script prior to the loop instruction (usually a FOR loop, in a batch script), and using an exclamation mark (!) instead of a percent sign (%) in the variable's name:
will print
The syntax %%a in (1,1,2)
causes the loop to run 2 times: on the first occasion, the variable bears its initial value of 'Hello', but on the second pass through the loop - having executed the second SET instruction as the last action on the 1st pass - this has changed to the revised value 'Goodbye'.
Advanced variable substitution
Now, an advanced technique. Using the CALL
command allows the batch command processor to expand a variable located on the same line of the script. This can deliver multilevel expansion, by repeated CALL and modifier use.
This is useful in, for example, a FOR loop. As in the following example, where we have a numbered list of variables:
'c:MyFilestest1.txt' 'c:MyFilestest2.txt' 'c:MyFilestest3.txt'
We can achieve this using the following FOR loop:
Output:
Note that the variable !i!
is first expanded to its initial value, 1, then the resulting variable, %1, is expanded to its actual value of c:MyFilestest1.txt
. This is double expansion of the variable i
. On the next line, i
is again double expanded, by use of the CALL ECHO
command together with the %%
variable prefix, then printed to the screen (i.e. displayed on screen).
On each successive pass through the loop, the initial number is increased by 1 (due to the code i+=1
). Thus it increases to 2
on the 2nd pass through the loop, and to 3
on the 3rd pass. Thus the string echoed to the screen alters with each pass.
Declare multiple variables
When multiple variables are defined at the beginning of the batch, a short definition form may be used by employing a replacement string.
Note in the above example, variables are natively alphabetically sorted, when printed to screen.
Using a Variable as an Array
It is possible to create a set of variables that can act similar to an array (although they are not an actual array object) by using spaces in the SET
statement:
Result:
It is also possible to declare your variable using indexes so you may retrieve specific information. This will create multiple variables, with the illusion of an array:
Result:
Note that in the example above, you cannot reference var
without stating what the desired index is, because var
does not exist in its own. This example also uses setlocal enabledelayedexpansion
in conjunction with the exclamation points at !var[%%a]!
. You can view more information about this in the Variable Substitution Scope Documentation.
Operations on Variables
The final value of var
is 20.
The second line is not working within a command block used for example on an IF condition or on a FOR loop as delayed expansion would be needed instead of standard environment variable expansion.
Here is another, better way working also in a command block:
The command prompt environment supports with signed 32-bit integer values:
- addition
+
and+=
- subtraction
-
and-=
- multiplication
*
and*=
- division
/
and/=
- modulus division
%
and%=
- bitwise AND
&
- bitwise OR
|
- bitwise NOT
~
- bitwise XOR
^
- bitwise left shift
<<
- bitwise right shift
>>
- logical NOT
!
- unary minus
-
- grouping with
(
and)
The Windows command interpreter does not support 64-bit integer values or floating point values in arithmetic expressions.
Note: The operator %
must be written in a batch file as %%
to be interpreted as operator.
In a command prompt window executing the command line set /A Value=8 % 3
assigns the value 2
to environment variable Value
and additionally outputs 2
.
In a batch file must be written set /A Value=8 %% 3
to assign the value 2
to environment variable Value
and nothing is output respectively written to handle STDOUT (standard output). A line set /A Value=8 % 3
in a batch file would result in error message Missing operator on execution of the batch file.
The environment requires the switch /A
for arithmetic operations only, not for ordinary string variables.
Every string in the arithmetic expression after set /A
being whether a number nor an operator is automatically interpreted as name of an environment variable.
For that reason referencing the value of a variable with %variable%
or with !variable!
is not necessary when the variable name consists only of word characters (0-9A-Za-z_) with first character not being a digit which is especially helpful within a command block starting with (
and ending with a matching )
.
Numbers are converted from string to integer with C/C++ function strtol with base
being zero which means automatic base determination which can easily result in unexpected results.
Batch Read Line From File Into Variable Time
Example:
The output of this example is:
Batch Read Line From File Into Variable Size
Variables not defined on evaluation of the arithmetic expression are substituted with value 0.
Setting variables from an input
Using the /p
switch with the SET
command you can define variables from an Input.
This input can be a user Input (keyboard) :
Which can be simplified like this :
Or you can get the input from a file :
in this case you'll get the value of the first line from file.txt
Getting the value of various line in a file :