If Noti Batchfiles



  • The following code, which works in batch files for all MS-DOS, Windows and OS/2 versions, uses an alternative way to show if a variable is defined or not: IF '%MyVar%' (ECHO MyVar is NOT defined) ELSE (ECHO MyVar IS defined).
  • Most (but not all) OS/2 and NT commands return a non-zero return code (errorlevel) on failure. Don't count on it in DOS, though. Page last uploaded: 2018-12-20, 10:48.

The for command accepts options when the /f flag is used. Here's a list of options that can be used: delims=x Delimiter character(s) to separate tokens. Skip=n Number of lines to skip at the beginning of file and text strings. @echo off if exist C:set2.txt echo 'File exists' if exist C:set3.txt (echo 'File exists') else (echo 'File does not exist') Output. Let’s assume that there is a file called set2.txt in the C drive and that there is no file called set3.txt. Then, following will be the output of the above code. 'File exists' 'File does not.

In this tutorial, you will learn about batch file variables and how they are used in batch file programming or scripting. You will also learn about the scope of variables in batch files.

Batch variables: Syntax
Batch variables: Example
Global variables vs Local variables
Batch if not exist multiple files

Batch file variables don’t need a declaration, in fact, the value is directly assigned to a variable using SET command.

Batch file variables – Syntax

Besides some reserved words (these predefined commands should not be used), any word or letter can be used as a variable.

Here is how the batch variables are declared.

Note: DOS or Batch commands are not case sensitive and ‘/A’ is used for assigning numeric values. Uninitialized variables are empty strings in batch files.

Set command overwrites any existing variables. For example, dynamic variables like %DATE% , %TEMP%, %CD% and others seem so fancy that you ought to use these variables. But note that these dynamic variables act like commands in DOS and overwriting these variables can alter their meanings.

So it’s always better to verify you aren’t using any system variables. But how do verify it?

How to verify if batch variables are defined already?

Here is how we can check if a variable is defined or not in DOS.

Go through our batch files if else tutorial, if you are not familiar with the batch file if-else statements.

Batch file variables – Example

This script will generate following output:

PAUSE is used to hold the screen until and it waits for user’s input.

Using whitespace between variable and value.SET name=Apple will work but SET name = Apple will not.

Now that you know how variables are used in batch file programs, let’s discuss global and local variables in batch files.

Variable scope in Batch files: Global variables and Local variables

As the name goes, global variable means a variable that can be accessed from anywhere in the program and local variable is the one that has limited scope or can be accessed from locally defined sections. By default, all the variables in batch file programs are GLOBAL.

Like any other programming language, Batch or DOS programming also has a definition for global and local variables.

As we mentioned, by default all the variables are global in a batch script, but they can be used as the local variable by using SETLOCAL command. Any variable assigned in between SETLOCAL and ENDLOCAL is taken as a local variable and its scope terminates and the variable is destroyed as soon as the ENDLOCAL statement is executed.

Following example will clear the concept of the local and global variable in batch file programming.

Example

Noti

This will generate following output:

So it works in a cool way.

Now let’s see what happens when we try to use a local variable beyond its scope i.e using after ENDLOCAL.

Example

In this program, var2 is a local variable and when we try to access it after ENDLOCAL is executed, the following happens.

So as seen in this output, when we try to use local variable beyond its scope, instead of executing commands with the local variable, the ECHO is turned off.

Declaration

To create a simple variable and assign it to a value or string use the SET command:

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!

Quotation marks used will be included in the variable's value:

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

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.

If Noti Batchfiles

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:

Batch File If Not Exist

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

Not

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

Useful Batch Files

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.

Batch Files If Not Exist

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 )

If In Batch File

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.

Example:

The output of this example is:

Variables not defined on evaluation of the arithmetic expression are substituted with value 0.

Batch File If Not Defined

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 :

Batch If Not Exist Multiple Files

in this case you'll get the value of the first line from file.txt

Getting the value of various line in a file :

If Noti Batch Files Rar