Dos - (Environment) Variable

About

How to manage variable in dos.

Naming convention

A variable name:

  • must only be made up of:
    • alphabetic characters,
    • numeric characters
    • and underscores,
  • cannot begin with a numeric character.
  • cannot be a system variable (such as if, for,…)

Management

Show

One variable

echo %myVariable%

of when delayed variables expansion is used.

echo !myVariable!

All variables (with optional pattern filtering)

Use the set command with or without a search term to filter the output:

set  <search term>

Example:

set W
windir=C:\Windows
windows_tracing_flags=3
windows_tracing_logfile=C:\BVTBin\Tests\installpackage\csilogfile.log

Set

A session variable

In line

A session variable has the scope of the console. If the console is closed the variable will be deleted.

set myVariable=myValue
from a file

with Dos - For Statement

for /f "delims=" %%x in (myFile.txt) do set myVariable=%%x

where:

An environment variable

If you want to preserve the value of a variable through several console, you have to set an environment variable with the setx command.

(Unset|Delete) a variable

  • Create a variable
set test=1
>echo %test%
1
  • Delete it
>set test=
>set test
Environment variable test not defined

Scope

By using the set command, the variable have a session scope. If you want a global scope, you must use the setx command

And in an block, the set command will not set the expected value if you don't use the Delayed environment variable expansion.

How to

Test if a variable is set

With the if defined variable statement.

Example:

if not defined v (echo v is not defined) else echo %v%
v is not defined
set v=Call Me Nico
if not defined v (echo v is not defined) else echo %v%
Call Me Nico

Get a sub-string of a variable

set test=123456
echo %test:~1,5%

where:

  • the first number defines the first position (default to 0)
  • the second number defines the number of character to return (default to the length of the variable)
23456

Unset multiple variables at once

By using the command parsing possibility of the for command. I have the following variable that I want to (unset|delete)

set HI
HI_HOME=D:\
HI_WORKING_DIRECTORY=D:\\temp
HI_WORKSPACE=D:\\workspace

You can do it with the following snippet:

FOR /F "usebackq delims==" %i IN (`set HI`) DO set %i=

The command must be between back quoted characters

Concat

set 1=Hello & echo %1% Nico 

Powered by ComboStrap