- Batch Script — Variables
- Command Line Arguments
- Set Command
- Syntax
- Example
- Output
- Working with Numeric Values
- Local vs Global Variables
- Example
- Output
- Working with Environment Variables
- /* steve jansen */
- // another day in paradise hacking code and more
- Windows Batch Scripting: Variables
- Variable Declaration
- Variable Assignment
- Reading the Value of a Variable
- Listing Existing Variables
- Variable Scope (Global vs Local)
- Special Variables
- Command Line Arguments to Your Script
- Tricks with Command Line Arguments
- Some Final Polish
- Comments
- Guides
- Recent Posts
- Social Stuff
- How to set commands output as a variable in a batch file
- 9 Answers 9
- In a Batch file
- On the Command Line
- Explanation
- And some tricks
Batch Script — Variables
There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command.
Command Line Arguments
Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on.
The following example shows a batch file which accepts 3 command line arguments and echo’s them to the command line screen.
If the above batch script is stored in a file called test.bat and we were to run the batch as
Following is a screenshot of how this would look in the command prompt when the batch file is executed.
The above command produces the following output.
If we were to run the batch as
The output would still remain the same as above. However, the fourth parameter would be ignored.
Set Command
The other way in which variables can be initialized is via the ‘set’ command. Following is the syntax of the set command.
Syntax
variable-name is the name of the variable you want to set.
value is the value which needs to be set against the variable.
/A – This switch is used if the value needs to be numeric in nature.
The following example shows a simple way the set command can be used.
Example
In the above code snippet, a variable called message is defined and set with the value of «Hello World».
To display the value of the variable, note that the variable needs to be enclosed in the % sign.
Output
The above command produces the following output.
Working with Numeric Values
In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch.
The following code shows a simple way in which numeric values can be set with the /A switch.
We are first setting the value of 2 variables, a and b to 5 and 10 respectively.
We are adding those values and storing in the variable c.
Finally, we are displaying the value of the variable c.
The output of the above program would be 15.
All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files.
The above command produces the following output.
Local vs Global Variables
In any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed.
DOS scripting also has a definition for locally and globally scoped variables. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script. The following example shows the difference when local and global variables are set in the script.
Example
Few key things to note about the above program.
The ‘globalvar’ is defined with a global scope and is available throughout the entire script.
The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed.
Output
The above command produces the following output.
You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the ‘var’ variable will no longer exist.
Working with Environment Variables
If you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications.
The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output.
/* steve jansen */
// another day in paradise hacking code and more
Windows Batch Scripting: Variables
Today we’ll cover variables, which are going to be necessary in any non-trivial batch programs. The syntax for variables can be a bit odd, so it will help to be able to understand a variable and how it’s being used.
Variable Declaration
DOS does not require declaration of variables. The value of undeclared/uninitialized variables is an empty string, or «» . Most people like this, as it reduces the amount of code to write. Personally, I’d like the option to require a variable is declared before it’s used, as this catches silly bugs like typos in variable names.
Variable Assignment
The SET command assigns a value to a variable.
NOTE: Do not use whitespace between the name and value; SET foo = bar will not work but SET foo=bar will work.
The /A switch supports arthimetic operations during assigments. This is a useful tool if you need to validated that user input is a numerical value.
A common convention is to use lowercase names for your script’s variables. System-wide variables, known as environmental variables, use uppercase names. These environmental describe where to find certain things in your system, such as %TEMP% which is path for temporary files. DOS is case insensitive, so this convention isn’t enforced but it’s a good idea to make your script’s easier to read and troubleshoot.
WARNING: SET will always overwrite (clobber) any existing variables. It’s a good idea to verify you aren’t overwriting a system-wide variable when writing a script. A quick ECHO %foo% will confirm that the variable foo isn’t an existing variable. For example, it might be tempting to name a variable “temp”, but, that would change the meaning of the widely used “%TEMP%” environmental varible. DOS includes some “dynamic” environmental variables that behave more like commands. These dynamic varibles include %DATE% , %RANDOM% , and %CD% . It would be a bad idea to overwrite these dynamic variables.
Reading the Value of a Variable
In most situations you can read the value of a variable by prefixing and postfixing the variable name with the % operator. The example below prints the current value of the variable foo to the console output.
There are some special situations in which variables do not use this % syntax. We’ll discuss these special cases later in this series.
Listing Existing Variables
The SET command with no arguments will list all variables for the current command prompt session. Most of these varaiables will be system-wide environmental variables, like %PATH% or %TEMP% .
NOTE: Calling SET will list all regular (static) variables for the current session. This listing excludes the dynamic environmental variables like %DATE% or %CD% . You can list these dynamic variables by viewing the end of the help text for SET, invoked by calling SET /?
Variable Scope (Global vs Local)
By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL , any variable assignments revert upon calling ENDLOCAL , calling EXIT , or when execution reaches the end of file (EOF) in your script.
This example demonstrates changing an existing variable named foo within a script named HelloWorld.cmd . The shell restores the original value of %foo% when HelloWorld.cmd exits.
A real life example might be a script that modifies the system-wide %PATH% environmental variable, which is the list of directories to search for a command when executing a command.
Special Variables
There are a few special situations where variables work a bit differently. The arguments passed on the command line to your script are also variables, but, don’t use the %var% syntax. Rather, you read each argument using a single % with a digit 0-9, representing the ordinal position of the argument. You’ll see this same style used later with a hack to create functions/subroutines in batch scripts.
There is also a variable syntax using ! , like !var! . This is a special type of situation called delayed expansion. You’ll learn more about delayed expansion in when we discuss conditionals (if/then) and looping.
Command Line Arguments to Your Script
You can read the command line arguments passed to your script using a special syntax. The syntax is a single % character followed by the ordinal position of the argument from 0 – 9 . The zero ordinal argument is the name of the batch file itself. So the variable %0 in our script HelloWorld.cmd will be “HelloWorld.cmd”.
The command line argument variables are * %0 : the name of the script/program as called on the command line; always a non-empty value * %1 : the first command line argument; empty if no arguments were provided * %2 : the second command line argument; empty if a second argument wasn’t provided * …: * %9 : the ninth command line argument
NOTE: DOS does support more than 9 command line arguments, however, you cannot directly read the 10th argument of higher. This is because the special variable syntax doesn’t recognize %10 or higher. In fact, the shell reads %10 as postfix the %0 command line argument with the string “0”. Use the SHIFT command to pop the first argument from the list of arguments, which “shifts” all arguments one place to the left. For example, the the second argument shifts from position %2 to %1 , which then exposes the 10th argument as %9 . You will learn how to process a large number of arguments in a loop later in this series.
Tricks with Command Line Arguments
Command Line Arguments also support some really useful optional syntax to run quasi-macros on command line arguments that are file paths. These macros are called variable substitution support and can resolve the path, timestamp, or size of file that is a command line argument. The documentation for this super useful feature is a bit hard to find – run ‘FOR /?’ and page to the end of the output.
I removes quotes from the first command line argument, which is super useful when working with arguments to file paths. You will need to quote any file paths, but, quoting a file path twice will cause a file not found error.
fI is the full path to the folder of the first command line argument
fsI is the same as above but the extra s option yields the DOS 8.3 short name path to the first command line argument (e.g., C:\PROGRA
1 is usually the 8.3 short name variant of C:\Program Files ). This can be helpful when using third party scripts or programs that don’t handle spaces in file paths.
dpI is the full path to the parent folder of the first command line argument. I use this trick in nearly every batch file I write to determine where the script file itself lives. The syntax SET parent=%
dp0 will put the path of the folder for the script file in the variable %parent% .
nxI is just the file name and file extension of the first command line argument. I also use this trick frequently to determine the name of the script at runtime. If I need to print messages to the user, I like to prefix the message with the script’s name, like ECHO %
n0: some message instead of ECHO some message . The prefixing helps the end user by knowing the output is from the script and not another program being called by the script. It may sound silly until you spend hours trying to track down an obtuse error message generated by a script. This is a nice piece of polish I picked up from the Unix/Linux world.
Some Final Polish
I always include these commands at the top of my batch scripts:
The SETLOCAL command ensures that I don’t clobber any existing variables after my script exits. The ENABLEEXTENSIONS argument turns on a very helpful feature called command processor extensions. Trust me, you want command processor extensions. I also store the name of the script (without the file extension) in a variable named %me% ; I use this variable as the prefix to any printed messages (e.g. ECHO %me%: some message ). I also store the parent path to the script in a variable named %parent% . I use this variable to make fully qualified filepaths to any other files in the same directory as our script.
Posted by Steve Jansen Mar 1 st , 2013 batch, scripting, shell, windows
Comments
Hi, I’m Steve. I’m a software developer loving life in Charlotte, NC, an (ISC) 2 CSSLP and an avid fan of Crossfit.
And, no, I’m not Steve Jansen the British jazz drummer, though that does sound like a sweet career.
Guides
Recent Posts
Social Stuff
- @steve-jansen on GitHub
- @steve-jansen on StackOverflow
- @steve-jansen ProTips on Coderwall
- @steve-jansen on Microsft Connect
- @steve-jansen on ASP.NET User Voice
- Subscribe via RSS
Copyright © 2015 — Steve Jansen — Powered by Octopress
How to set commands output as a variable in a batch file
Is it possible to set a statement’s output of a batch file to a variable, for example:
9 Answers 9
I always use the USEBACKQ so that if you have a string to insert or a long file name, you can use your double quotes without screwing up the command.
Now if your output will contain multiple lines, you can do this
I found this thread on that there Interweb thing. Boils down to:
You can also redirect the output of a command to a temporary file, and then put the contents of that temporary file into your variable, likesuchashereby. It doesn’t work with multiline input though.
Credit to the thread on Tom’s Hardware.
in a single line:
the command output will be set in %g then in VAR.
To Write a file
note; having spaces before the <> character causes a space to be added at the end of the variable, also
To add to a file,like a logger program, First make a file with a single enter key in it called e.txt
your log will look like this
Anyways a couple useful things
These answers were all so close to the answer that I needed. This is an attempt to expand on them.
In a Batch file
If you’re running from within a .bat file and you want a single line that allows you to export a complicated command like jq -r «.Credentials.AccessKeyId» c:\temp\mfa-getCreds.json to a variable named AWS_ACCESS_KEY then you want this:
On the Command Line
If you’re at the C:\ prompt you want a single line that allows you to run a complicated command like jq -r «.Credentials.AccessKeyId» c:\temp\mfa-getCreds.json to a variable named AWS_ACCESS_KEY then you want this:
Explanation
The only difference between the two answers above is that on the command line, you use a single % in your variable. In a batch file, you have to double up on the percentage signs (%%).
Since the command includes colons, quotes, and parentheses, you need to include the USEBACKQ line in the options so that you can use backquotes to specify the command to run and then all kinds of funny characters inside of it.
If you don’t want to output to a temp file and then read into a variable, this code stores result of command direct into a variable:
If you want to enclose search string in double quotes:
If you want to store this code in a batch file, add an extra % symbol:
A useful example to count the number of files in a directory & store in a variable: (illustrates piping)
Note the use of single quotes instead of double quotes » or grave accent ` in the command brackets. This is cleaner alternative to delims , tokens or usebackq in for loop.
Tested on Win 10 CMD.
Some notes and some tricks.
The ‘official’ way to assign result to a variable is with FOR /F though in the other answers is shown how a temporary file can be used also.
For command processing FOR command has two forms depending if the usebackq option is used. In the all examples below the whole output is used without splitting it.
and if used directly in the console:
%%A is a temporary variable available only on the FOR command context and is called token.The two forms can be useful in case when you are dealing with arguments containing specific quotes. It is especially useful with REPL interfaces of other languages or WMIC. Though in both cases the expression can be put in double quotes and it still be processed.
Here’s an example with python (it is possible to transition the expression in the brackets on a separate line which is used for easier reading):
To use an assigned variable in the same FOR block check also the DELAYED EXPANSION
And some tricks
To save yourself from writing all the arguments for the FOR command you can use MACRO for assigning the result to variable:
the first argument to the macro is the command and the second the name of the variable we want to use and both are separated by , (comma). Though this is suitable only for straight forward scenarios.
If we want a similar macro for the console we can use DOSKEY
DOSKEY does accept double quotes as enclosion for arguments so this also is useful for more simple scenarios.
FOR also works well with pipes which can be used for chaining commands (though it is not so good for assigning a variable.