Использование переменных в командной строке windows

На чтение 5 мин Просмотров 15.2к. Опубликовано

Объявление собственных переменных является неотъемлемой часть практически любого языка программирования, так в языке vbscript они объявляются с помощью ключевого слова dim, а в jscript – используется ключевое слово var.

Переменные командной строки Windows представляют немного другой характер, тут нельзя объявить группу переменных cmd, или же сразу присвоить значения нескольким переменным в командной строке. Давайте посмотрим на следующие строчки кода:

set Var1=D:\Work
set Var2=100
set Var3="Привет Мир!!!"

В данном примере, с помощью ключевого слова cmd set мы поэтапно объявили три переменные (Var1, Var2 и Var3), как и в языке vbscript, в cmd регистр символов не играет роли, поэтому, данные строчки выведут фразу «Привет Мир!!!»

set Var3
set VAR3
set vAr3

или

echo %Var3%
echo %VAR3%
echo %vAr3%

Стоит учитывать один момент, запись

и

это не одно и тоже, то есть, в первом случае мы создаем cmd переменную «var1», а во втором – «var1 «. С присвоением значений аналогичная ситуация, так что обращайте внимание на пробел!!!

Видим, что бы вывести значение переменной с помощью функции Echo, мы заключаем ее в символ «%», для set – просто прописываем ее имя, так же стоит учитывать, что всем переменным присваивается строковой тип.

Если вы запустите на выполнение команду cmd set, которая выводит список всех переменных и их значений в текущем сеансе, то увидите, что там будут присутствовать и только что созданные cmd переменные и переменные среды. Мы сможем обращаться к ним на протяжение всего сеанса работы.

Что бы очистить переменные в командной строке Windows от их содержимого, нужно просто присвоить пустое значение:

Мы просто после имени прописали знак равенства и все. Стоит помнить, что если в таких языках программирования как vbscript и jscript присвоение пустого значения переменной не влияет на ее существование, то в командной строке происходит полное ее удаление, то есть, команда:

просто выведет строчку %Var3%, а команда

Выведет сообщение «переменная среды var3 не определена»

Стоит учитывать тот момент, что если мы хотим, что бы переменная командной строки Windows содержала специальные символы (например, @ < > & | ^ ), то их нужно экранировать.  В языке jscript для вывода специальных символов используются esc-последовательности, в командной строке специальный символ экранируется с помощью «^»:

set Var4=100 ^&3 = 5
set Var5=100 ^^3

В данном примере мы экранировали символы & и ^, тем самым присвоив фразы:

«100 & 3 = 5»
«100 ^3»

Стоит обратить внимание, что если мы попытаемся вывести значения данных переменных с помощью функции cmd set, то проблем не возникнет, но если будет использовать функцию echo, то получим совсем не тот результат, что ожидали. Так, при попытке выполнить следующую команду:

Получим предупреждение:

100
«3» не является внутренней или внешней командой, исполняемой программой или командным файлом.

Это происходит из-за повторного анализа спец-символов при использовании функции echo. Надо просто прописать символ «^» экранирования не один раз, а трижды:

set Var4=100 ^^^&3 = 5
set Var5=100 ^^^^3

Теперь при выполнении кода:

все пройдет успешно.

Как и в сценариях сервера Windows Script Host, переменные в командной строке Windows могут содержать заданную область видимости.

Область видимости – блок кода, за пределами которого нельзя получить доступ к переменным, объявленным в нем. Довольно ясно значение области видимости проявляется при роботе с функциями, по этому вопросу можете прочить статью «Урок 3 по JScript: Объявление пользовательских функций«.

Понятно, что переменные cmd, созданные в текущем окне командной строки недоступна для других процессов, но, есть возможность задать ограничения еще большие.

переменные командной строки windows

Что бы задать локальную область видимости, используется блок SETLOCAL … ENDLOCAL. Все cmd переменные командной строки Windows, объявленные в середине данного блока не будут видны за его пределами. Откройте редактор (я использую редактор Notepad++, так как он сразу подсвечивает код), и пропишите в нем следующие строчки кода:

@echo off
set var1=0
rem Начало локализации
setlocal
set var1=5
echo Lokalnaya: var1= %var1%
endlocal 
echo Globalnaya: var1= %var1%

Видим, что вначале мы объявили var1 и присвоили ей значение 0, далее мы снова объявили переменную с аналогичным именем, но уже в блоке SETLOCAL … ENDLOCAL. В сценарии происходит вывод значения как локальной, так и глобальной var1. Я специально использовал латинские знаки, что бы у вас в случае чего не выводились крякозябры.

In Windows Command Prompt (cmd), a variable allows you to store and reference data, which can simplify command usage and enhance scripts.

set MY_VARIABLE=Hello, World!
echo %MY_VARIABLE%

What are CMD Variables?

CMD variables are placeholders used to store data in the command-line interface or within batch scripts. They enable users to manage information dynamically, making scripts more powerful and flexible. Understanding how to effectively use variables in CMD is crucial for efficient scripting and automation of repetitive tasks.

Variables in CMD can be categorized into two types: local variables and global variables. Local variables exist only within the context of a script or a command block, while global variables can be accessed throughout the session. This distinction is essential when designing scripts that may have different scopes and variable lifetimes.

Trace Cmd: A Quick Guide to Command-Line Tracing

Trace Cmd: A Quick Guide to Command-Line Tracing

How to Declare and Use Variables in CMD

Declaring Variables

The syntax for declaring a variable in CMD is straightforward. You can declare a variable using the `set` command followed by the variable name and its value. The value assigned can be a string, number, or path depending on your needs.

For example:

set myVar=HelloWorld

In this case, `myVar` is now a variable storing the text «HelloWorld.»

Accessing Variables

Once a variable is declared, accessing its value is done using percent signs surrounding the variable name. This syntax allows CMD to retrieve and display the variable’s content.

For example:

echo %myVar%

When executing this command, the output will be:

HelloWorld

Mastering Route Table Cmd: A Quick Guide

Mastering Route Table Cmd: A Quick Guide

Using CMD Variables in Scripts

Creating a Basic CMD Script

To showcase the power of variables, you can create a simple CMD script. This involves writing a sequence of commands within a text file, saving it with a `.cmd` or `.bat` extension, and executing it from the command prompt.

Here’s an example script that utilizes variables effectively:

@echo off
set name=John
echo Hello, %name%
pause

In this script:

  • `@echo off` disables command echoing, making the output cleaner.
  • A variable `name` is created, holding the value «John».
  • The `echo` command displays a personalized greeting incorporating the variable.

Variables in CMD File Variables

Understanding Scope and Lifetime

When working with batch files, understanding variable scope is crucial. Variables declared inside a script remain local to that script unless explicitly passed or defined globally. This means their values do not persist once the script finishes executing.

Example of Scope

The following example demonstrates how scope affects the variables in a batch file:

@echo off
set myVar=GlobalValue
call :MySubRoutine
echo After Subroutine: %myVar%
goto :EOF

:MySubRoutine
set myVar=LocalValue
exit /b

In this script:

  • `myVar` is first assigned the value «GlobalValue.»
  • When calling the subroutine `:MySubRoutine`, it assigns «LocalValue» to `myVar`.
  • However, when the main portion continues, the output remains «GlobalValue,» indicating that the local assignment in the subroutine did not affect the global scope.

View Environment Variables Cmd with Ease

View Environment Variables Cmd with Ease

Manipulating CMD Variables

Variable Expansion

Variable expansion is a powerful feature in CMD scripting. It allows one to manipulate the data held in variables further, particularly through techniques like delayed expansion. This is especially useful when working within loops where you need to set a variable’s value and use it later in the same block.

To enable delayed expansion, you can use `setlocal enabledelayedexpansion`. Here’s an example illustrating this concept:

setlocal enabledelayedexpansion
set count=5
for /L %%i in (1,1,!count!) do echo %%i
endlocal

In this instance, `!count!` is used instead of `%count%` to reference the variable’s value during the loop.

String Manipulation with Variables

Variables in CMD also allow for simple string manipulation, like extracting substrings. For instance, to obtain a specific portion of a string stored in a variable, you can use the syntax:

set myVar=HelloWorld
echo Substring: %myVar:~0,5%

In this example, the command will output «Hello» since it extracts the first five characters from `myVar`.

Check Environment Variables in Cmd: A Quick Tutorial

Check Environment Variables in Cmd: A Quick Tutorial

Common Use Cases for CMD Variables

Automating Tasks

One of the most significant advantages of using variables in CMD is automating repetitive tasks. Through the manipulation of variables, you can loop through values, making your scripts dynamic and efficient.

Consider this loop example:

@echo off
set count=3
for /L %%i in (1,1,%count%) do (
    echo Iteration %%i
)

Here, the script outputs an iteration message three times, thanks to the dynamic counting achieved through variables.

Passing Variables Between Scripts

In scenarios where CMD scripts need to cooperate, passing variables between scripts becomes necessary. This can be accomplished by calling one script from another, as shown below:

:: script1.cmd
set myVar=PassedValue
call script2.cmd

:: script2.cmd
echo The value is: %myVar%

In this case, `script1.cmd` sets a variable, and `script2.cmd` can access it, demonstrating inter-script communication.

Mastering Cmd Set Variable: Quick Guide for Beginners

Mastering Cmd Set Variable: Quick Guide for Beginners

Best Practices for Using CMD Variables

Naming Conventions

When selecting names for your CMD variables, adopting a clear and consistent naming convention is vital for readability and maintainability. Use meaningful names that convey the data contained within the variable. For example, `username` is preferable over `var1`.

Avoiding Common Pitfalls

While working with variable cmd, some common mistakes can hinder your scripting experience. Here are a few to watch for:

  • Unintended Overwrites: Be cautious not to overwrite important variables unintentionally.
  • Scope Confusion: Ensure you understand the lifetimes of your variables to avoid unexpected behavior.
  • Improper Expansion: Remember to use delayed expansion when necessary to avoid referencing outdated variable values.

Trace Cmd Command: A Quick Guide to Network Tracing

Trace Cmd Command: A Quick Guide to Network Tracing

Conclusion

In summary, mastering the use of variables in CMD unlocks a more dynamic and powerful approach to scripting in the command prompt. From basic declarations and access to advanced manipulation techniques, the potential for automation and efficiency in your tasks is significant. As you practice and apply these concepts, you’ll find that the time invested in learning about CMD variables pays off, enhancing your overall command-line skills.

Explore additional resources and tutorials to deepen your understanding, and don’t hesitate to engage with communities passionate about CMD scripting. Happy scripting!

декларация

Чтобы создать простую переменную и присвоить ее значению или строке, используйте команду SET :

SET var=10

Здесь код объявляет новую переменную var со значением 10 . По умолчанию все переменные хранятся внутри строки в виде строк; это означает, что значение 10 не отличается от foo1234 или Hello, World!

Заметки о кавычках

Используемые котировочные знаки будут включены в значение переменной:

SET var="new value"             <-- %var% == '"new value"'

Пространства в переменных

Пакетный язык рассматривает пространства как приемлемые части имен переменных. Например, set var = 10 приведет к переменной var которая содержит значение 10 (обратите внимание на дополнительное пространство справа от var и слева от 10).

Использование кавычек для устранения пробелов

Чтобы предотвратить пробелы, используйте кавычки вокруг всего задания; имя переменной и значение. Это также предотвращает случайные конечные пробелы в конце строки (символ обозначает пробел):

SET␣var=my␣new␣value␣           <-- '%var%' == 'my new value '
SET␣"var=my␣new␣value"␣         <-- '%var%' == 'my new value'

Кроме того, используйте кавычки при объединении нескольких операторов с помощью & или | — альтернативно, поместите символ непосредственно после окончания значения переменной:

SET var=val & goto :next        <-- '%var%' == 'val '
SET "var=val" & goto :next      <-- '%var%' == 'val'
SET var=val& goto :next         <-- '%var%' == 'val'

использование

echo %var%

Этот код будет повторять значение var

Если используется setLocal EnableDelayedExpansion , следующее будет setLocal EnableDelayedExpansion значение var (стандартное выражение% var% не будет работать в этом контексте).

echo !var!

В пакетных файлах переменные могут использоваться в любом контексте, в том числе в составе команд или частей других переменных. Вы не можете вызывать переменную до ее определения.

Использование переменных в качестве команд:

set var=echo
%var% This will be echoed

Использование переменных в других переменных:

set var=part1
set %var%part2=Hello
echo %part1part2%

Переменная замена

В отличие от других языков программирования, в пакетном файле переменная заменяется ее фактическим значением до запуска командного скрипта. Другими словами, замена выполняется, когда скрипт считывается в память командным процессором, а не при последующем запуске сценария.

Это позволяет использовать переменные как команды внутри скрипта и как часть других имен переменных в скрипте и т. Д. «Сценарий» в этом контексте является строкой или блоком кода, окруженным круглыми скобками: () .

Но это поведение означает, что вы не можете изменить значение переменной внутри блока!

SET VAR=Hello
FOR /L %%a in (1,1,2) do (
    ECHO %VAR%
    SET VAR=Goodbye
)

распечатает

Hello
Hello

поскольку (как вы видите, при просмотре сценария, запускаемого в окне команд), он вычисляется так:

SET VAR=Hello
FOR /L %%a in (1,1,2) do (
    echo Hello
    SET VAR=Goodbye
)

В приведенном выше примере команда ECHO оценивается как Hello когда скрипт считывается в память, поэтому скрипт будет эхом Hello навсегда, однако многие проходы выполняются через скрипт.

Способ достижения более «традиционного» поведения переменной (переменной, которая расширяется во время работы скрипта) заключается в том, чтобы включить «замедленное расширение». Это включает в себя добавление этой команды в скрипт перед инструкцией цикла (обычно цикл FOR, в пакетном скрипте) и использование восклицательного знака (!) Вместо знака процента (%) в имени переменной:

setlocal enabledelayedexpansion 
SET VAR=Hello
FOR /L %%a in (1,1,2) do (
    echo !VAR!
    SET VAR=Goodbye
)
endlocal

распечатает

Hello
Goodbye

Синтаксис %%a in (1,1,2) заставляет цикл работать 2 раза: в первом случае переменная несет свое начальное значение «Hello», но на втором проходе через цикл — выполнив второй SET как последнее действие на 1-м проходе — это изменилось на измененное значение «До свидания».

Расширенная подстановка переменных

Теперь, передовая техника. Использование команды CALL позволяет процессору команд партии расширять переменную, расположенную в той же строке сценария. Это может обеспечить многоуровневое расширение путем повторного использования CALL и модификатора.

Это полезно, например, для цикла FOR. Как и в следующем примере, где у нас есть нумерованный список переменных:

"c:\MyFiles\test1.txt" "c:\MyFiles\test2.txt" "c:\MyFiles\test3.txt"

Мы можем достичь этого, используя следующий цикл FOR:

setlocal enabledelayedexpansion
for %%x in (%*) do (
    set /a "i+=1"
    call set path!i!=%%~!i!
    call echo %%path!i!%%
)
endlocal

Выход:

c:\MyFiles\test1.txt
c:\MyFiles\test2.txt
c:\MyFiles\test3.txt

Обратите внимание, что переменная !i! сначала расширяется до его начального значения, 1, то результирующая переменная% 1 расширяется до ее фактического значения c:\MyFiles\test1.txt . Это двойное расширение переменной i . На следующей строке i снова удваивается, используя команду CALL ECHO вместе с префиксом переменной %% , затем печатается на экране (т.е. отображается на экране).

На каждом последующем проходе через цикл начальное число увеличивается на 1 (из-за кода i+=1 ). Таким образом, он увеличивается до 2 на 2 -м проходе через петлю и до 3 на 3 -м проходе. Таким образом, строка, отобранная на экран, изменяется с каждым проходом.

Объявить несколько переменных

Когда в начале партии задано несколько переменных, можно использовать короткую форму определения, используя заменяющую строку.

@echo off
set "vars=_A=good,_B=,_E=bad,_F=,_G=ugly,_C=,_H=,_I=,_J=,_K=,_L=,_D=6
set "%vars:,=" & set "%"

for /f %%l in ('set _') do echo %%l
exit /b

_A=good
_D=6
_E=bad
_G=ugly

Обратите внимание, что в приведенном выше примере переменные упорядочиваются в алфавитном порядке при печати на экран.

Использование переменной как массива

Можно создать набор переменных, которые могут действовать подобно массиву (хотя они не являются фактическим объектом массива), используя пробелы в инструкции SET :

@echo off
SET var=A "foo bar" 123
for %%a in (%var%) do (
    echo %%a
)
echo Get the variable directly: %var%

Результат:

A
"foo bar"
123
Get the variable directly: A "foo bar" 123

Также можно объявить переменную с помощью индексов, чтобы вы могли получить определенную информацию. Это создаст несколько переменных с иллюзией массива:

@echo off
setlocal enabledelayedexpansion
SET var[0]=A
SET var[1]=foo bar
SET var[2]=123
for %%a in (0,1,2) do (
    echo !var[%%a]!
)
echo Get one of the variables directly: %var[1]%

Результат:

A
foo bar
123
Get one of the variables directly: foo bar

Обратите внимание, что в приведенном выше примере вы не можете ссылаться на var не указывая, что такое желаемый индекс, потому что var не существует в своем собственном. Этот пример также использует setlocal enabledelayedexpansion в сочетании с восклицательными знаками в !var[%%a]! , Вы можете просмотреть дополнительную информацию об этом в документах с переменной заменой .

Операции над переменными

set var=10
set /a var=%var%+10
echo %var%

Конечное значение var равно 20.

Вторая строка не работает в командном блоке, используемом, например, в условии IF или в цикле FOR, поскольку требуется замедленное расширение вместо стандартного расширения переменной среды.

Вот еще один лучший способ работы в командном блоке:

set var=10
set /A var+=10
echo %var%

Среда командной строки поддерживает с подписанными 32-битными целыми значениями:

  • дополнение + и +=
  • вычитание - и -=
  • умножение * и *=
  • деление / и /=
  • модульное деление % и %=
  • побитовое И &
  • побитовое ИЛИ |
  • побитовое НЕ ~
  • побитовое XOR ^
  • побитовый сдвиг влево <<
  • побитовый сдвиг вправо >>
  • логическое НЕ !
  • унарный минус -
  • группировка с ( и )

Командный интерпретатор Windows не поддерживает 64-разрядные целочисленные значения или значения с плавающей запятой в арифметических выражениях.

Примечание . Оператор % должен быть записан в пакетном файле как %% который должен интерпретироваться как оператор.

В окне командной строки, выполняющем set /A Value=8 % 3 командной строки set /A Value=8 % 3 присваивается значение 2 переменной среды Value и дополнительно выводится 2 .

В пакетном файле необходимо записать set /A Value=8 %% 3 чтобы присвоить значение 2 переменной окружения Value и ничего не выводится, соответственно, для обработки STDOUT (стандартный вывод). Набор строк set /A Value=8 % 3 в пакетном файле приведет к появлению сообщения об ошибке Отсутствует оператор при выполнении командного файла.

Для среды требуется коммутатор /A для арифметических операций, а не для обычных строковых переменных.

Каждая строка в арифметическом выражении после set /A означает, что число или оператор автоматически интерпретируются как имя переменной среды.

По этой причине ссылка на значение переменной с %variable% или !variable! не требуется, когда имя переменной состоит только из словных символов (0-9A-Za-z_), причем первый символ не является цифрой, что особенно полезно в командном блоке, начиная с ( и заканчивая сопоставлением ) .

Числа преобразуются из строки в целое число с функцией C / C ++ strtol с base , равной нулю, что означает автоматическое определение базы, что может легко привести к неожиданным результатам.

Пример:

set Divided=11
set Divisor=3

set /A Quotient=Divided / Divisor
set /A Remainder=Divided %% Divisor

echo %Divided% / %Divisor% = %Quotient%
echo %Divided% %% %Divisor% = %Remainder%

set HexValue1=0x14
set HexValue2=0x0A
set /A Result=(HexValue1 + HexValue2) * -3

echo (%HexValue1% + %HexValue2%) * -3 = (20 + 10) * -3 = %Result%

set /A Result%%=7
echo -90 %%= 7 = %Result%

set OctalValue=020
set DecimalValue=12
set /A Result=OctalValue - DecimalValue

echo %OctalValue% - %DecimalValue% = 16 - 12 = %Result%

Результат этого примера:

11 / 3 = 3
11 % 3 = 2
(0x14 + 0x0A) * -3 = (20 + 10) * -3 = -90
-90 %= 7 = -6
020 - 12 = 16 - 12 = 4

Переменные, не определенные при оценке арифметического выражения, заменяются значением 0.

Установка переменных из ввода

Используя переключатель /p с помощью команды SET вы можете определить переменные из ввода.

Этот вход может быть пользователем Вход (клавиатура):

echo Enter your name : 
set /p name=
echo Your name is %name%

Который может быть упрощен следующим образом:

set /p name=Enter your name :
echo Your name is %name%

Или вы можете получить входные данные из файла:

set /p name=< file.txt

в этом случае вы получите значение первой строки из file.txt

Получение значения различной строки в файле:

(
   set /p line1=
   set /p line2=
   set /p line3=

) < file.txt

  • SS64
  • CMD
  • How-to

Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.

Syntax
      SET variable
      SET variable=string
      SET "variable=string"
      SET "variable="

      SET /A "variable=expression"
      SET /P variable=[promptString]
      SET "

Key
   variable   A new or existing environment variable name e.g. _num
   string     A text string to assign to the variable.
   /A         Arithmetic expression see full details below.
   /P         Prompt for user input.

Variable names are not case sensitive but the contents can be.

It is good practice to avoid using any delimiter characters (spaces, commas etc) in the variable name.

Delimiter characters can be used in the value if the complete assignment is surrounded with double quotes to prevent the delimiter being interpreted.

Any extra spaces around either the variable name or the string, will not be ignored, SET is not forgiving of extra spaces like many other scripting languages. So use SET alpha=beta, not SET alpha = beta

The first character of the name must not be numeric. It is a common practice to prefix variable names with either an underscore or a dollar sign _variable or $variable, these prefixes are not required but help to prevent any confusion with the standard built-in Windows Environment variables or any other command strings.

SET PATH… the command SET PATH is functionaly identical to the PATH command for modifying the user’s PATH variable, see the PATH page for more detail.

The CMD shell will fail to read an environment variable if it contains more than 8,191 characters.

SET is an internal command.
If Command Extensions are disabled all SET commands are disabled other than simple assignments like: _variable=MyText

Display a variable:

In most contexts, surround the variable name with %’s and the variable’s value will be used
e.g. To display the value of the _department variable with the
ECHO command:
ECHO %_department%

If the variable name is not found in the current environment then SET will set %ERRORLEVEL% to 1 .
This can be detected using IF ERRORLEVEL …

Including extra characters can be useful to show any white space:
ECHO [%_department%]
ECHO «%_department%«

Type SET without parameters to display all the current environment variables.

Type SET with a variable name to display that variable
SET _department

The SET command invoked with a string (and no equal sign) will display a wildcard list of all matching variables

Display variables that begin with ‘P’:
SET p

Display variables that begin with an underscore
SET _

Set a variable:

Example of storing a text string:

C:\> SET «_dept=Sales and Marketing»
C:\> set _
_dept=Sales and Marketing

Set a variable that contains a redirection character, note the position of the quotes which are not saved:

SET «_dept=Sales & Marketing»

One variable can be based on another, but this is not dynamic
E.g.

C:\> set «xx=fish»
C:\> set «msg=%xx% chips»
C:\> set msg
msg=fish chips

C:\> set «xx=sausage»
C:\> set msg
msg=fish chips

C:\> set «msg=%xx% chips»
C:\> set msg
msg=sausage chips

Avoid starting variable names with a number, this will avoid the variable being mis-interpreted as a parameter
%123_myvar% < > %1 23_myvar

To display undocumented system variables:

SET «

Values with Spaces — using Double Quotes

There is no hard requirement to add quotation marks even when assigning a value that includes spaces:

SET _variable=one two three
ECHO %_variable%

Adding quotation marks is a best practise and will account for any trailing spaces and special characters like ‘&’.
The variable contents will not include the surrounding quotes:

SET «_variable=one & two«
ECHO «%_variable%»

If you place quotation marks around just the value, then those quotes will be stored:

SET _variable=«one & two»
ECHO %_variable%

This can be used for long filenames:

SET _QuotedPath=«H:\Config files\config 64.xml«
COPY %_QuotedPath% C:\Demo\final.xml

Alternatively you can add quotes at the point where they are needed:

SET «_Filename=config 64.xml»
COPY «H:\Config files\%_Filename%» C:\Demo\final.xml

Variable names with spaces

A variable can contain spaces and also the variable name itself can contain spaces,
therefore the following assignment:
SET _var =MyText
will create a variable called «_var « ← note the trailing space.

Prompt for user input

The /P switch allows you to set a variable equal to a line of input entered by the user.
The Prompt string is displayed before the user input is read.

@echo off
Set /P _ans=Please enter Department: || Set _ans=NothingChosen
:: remove &’s and quotes from the answer (via string replace)
Set _ans=%_ans:&=%
Set _ans=%_ans:"=%
If "%_ans%"=="NothingChosen" goto sub_error
If /i "%_ans%"=="finance" goto sub_finance
If /i "%_ans%"=="hr" goto sub_hr goto:eof :sub_finance echo You chose the finance dept goto:eof :sub_hr echo You chose the hr dept
goto:eof :sub_error echo Nothing was chosen

Both the Prompt string and the answer provided can be left empty. If the user does not enter anything (just presses return) then the variable will be unchanged and the errorlevel will be set to 1.

The script above strips out any ‘&’ and » characters but may still break if the string provided contains both.
For user provided input, it is a good idea to fully sanitize any input string for potentially
problematic characters (unicode/smart quotes etc).

The CHOICE command is an alternative for user input, CHOICE accepts only one character/keypress, when selecting from a limited set of options it will be faster to use.

Echo a string with no trailing CR/LF

The standard ECHO command will always add a CR/LF to the end of each string displayed, returning the cursor to the start of the next line.
SET /P does not do this, so it can be used to display a string. Feed a NUL character into SET /P like this, so it doesn’t wait for any user input:

Set /P _scratch=»This is a message to the user » <nul

Place the first line of a file into a variable:

Set /P _MyVar=<MyFilename.txt
Echo %_MyVar%

The second and any subsequent lines of text in the file will be discarded.

In very early versions of CMD, any carriage returns/new lines (CR+LF) before the first line containing text were ignored.

Delete a variable

Type SET with just the variable name and an equals sign:

SET _department=

Better still, to be sure there is no trailing space after the = place the expression in parentheses or quotes:
(SET _department=)
  or
SET «_department=»

Arithmetic expressions (SET /a)

Placing expressions in «quotes» is optional for simple arithmetic but required for any expression using logical operators or parentheses.
A best practice is to use quotes around all SET /A expressions, then they will always be in place when needed.

When referring to a variable in your expression, SET /A allows you to omit the %’s so _myvar instead of %_myvar%

The expression to be evaluated can include the following operators:
For the Modulus operator use (%) on the command line, or in a batch script it must be doubled up to (%%) as below.
This is to distinguish it from a FOR parameter.

   +   Add                set /a "_num=_num+5"
   +=  Add variable       set /a "_num+=5"
   -   Subtract           set /a "_num=_num-5"
   -=  Subtract variable  set /a "_num-=5"
   *   Multiply           set /a "_num=_num*5"
   *=  Multiply variable  set /a "_num*=5"
   /   Divide             set /a "_num=_num/5"
   /=  Divide variable    set /a "_num/=5"
   %%  Modulus            set /a "_num=17%%5"
   %%= Modulus            set /a "_num%%=5"
   !   Logical negation  0 (FALSE) ⇨ 1 (TRUE) and any non-zero value (TRUE) ⇨ 0 (FALSE)
   ~   Bitwise invert
   &   AND                set /a "_num=5&3"    0101 AND 0011 = 0001 (decimal 1)
   &=  AND variable       set /a "_num&=3"
   |   OR                 set /a "_num=5|3"    0101 OR 0011 = 0111 (decimal 7)
   |=  OR variable        set /a "_num|=3"
   ^   XOR                set /a "_num=5^3"    0101 XOR 0011 = 0110 (decimal 6)
   ^=  XOR variable       set /a "_num=^3"
   <<  Left Shift.    (sign bit ⇨ 0) An arithmetic shift.
   >>  Right Shift.   (Fills in the sign bit such that a negative number always remains negative.)
                       Neither ShiftRight nor ShiftLeft will detect overflow.
   <<= Left Shift variable     set /a "_num<<=2"
   >>= Right Shift variable    set /a "_num>>=2"

  ( )  Parenthesis group expressions  set /a "_num=(2+3)*5"
   ,   Commas separate expressions    set /a "_num=2,_result=_num*5"

Any SET /A calculation that returns a fractional result will be rounded down to the nearest whole integer.

Floating point arithmetic is not supported but you can call PowerShell for that: powershell.exe 12.9999999 + 2105001.01
or in a batch file:
For /F %%G in (‘powershell.exe 12.9999999 + 2105001.01’) do Echo Result: %%G

If a variable name is specified as part of the expression, but is not defined in the current environment, then SET /a will use a value of 0.

SET /A arithmetic shift operators do not detect overflow which can cause problems for any non-trivial math, e.g. the bitwise invert often incorrectly reverses the + / — sign of the result.

See SET /a examples below and this forum thread for more.
also see SetX, VarSearch and VarSubstring for more on variable manipulation.

SET /A should work within the full range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647) but in practice for negative integers it will not go below -2,147,483,647 because the correct two’s complement result 2,147,483,648 would cause a positive overflow.

Examples

SET /A «_result=2+4»
(=6)

SET /A «_result=5»
(=5)
SET /A «_result+=5″
(=10)

SET /A «_result=2<<3″
(=16) { 2 Lsh 3 = binary 10 Lsh 3 = binary 10000 = decimal 16 }

SET /A «_result=5%%2″
(=1) { 5/2 = 2 + 2 remainder 1 = 1 }

SET /A «_var1=_var2=_var3=10»
(sets 3 variables to the same value — undocumented syntax.)

SET /A will treat any character string in the expression
as an environment variable name. This allows you to do arithmetic with environment
variables without having to type any % signs to get the values. SET /A «_result=5 + _MyVar«

Multiple calculations can be performed in one line, by separating each calculation with commas, for example:

Set «_year=1999»
Set /a «_century=_year/100, _next=_century+1»

The numbers must all be within the range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647) to handle larger numbers use PowerShell or VBScript.

You can also store a math expression in a variable and substitute in different values, rather like a macro.

SET «_math=(#+6)*5»
SET /A _result=»%_math:#=4%
Echo %_result%
SET /A _result=»%_math:#=10%
Echo %_result%

Leading Zero will specify Octal

Numeric values are decimal numbers, unless prefixed by
0x for hexadecimal numbers,
0 for octal numbers.

So 0x10 = 020 = 16 decimal

The octal notation can be confusing — all numeric values that start with zeros are treated as octal but 08 and 09 are not valid octal digits.
For example SET /a «_month=07» will return the value 7, but SET /a «_month=09» will return an error.

Permanent changes

Changes made using the SET command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed.
To permanently change a variable at the command line use SetX
or with the GUI: Control Panel ➞ System ➞ Environment ➞ System/User Variables

Changing a variable permanently with SetX will not affect any CMD prompt that is already open.
Only new CMD prompts will get the new setting.

You can of course use SetX in conjunction with SET to change both at the same time:

Set _Library=T:\Library\
SetX _Library T:\Library\ /m

Change the environment for other sessions

Neither SET nor SetX will affect other CMD sessions that are already running on the machine. This as a good thing, particularly on multi-user machines, your scripts won’t have to contend with a dynamically changing environment while they are running.

It is possible to add permanent environment variables to the registry (HKCU\Environment), but this is an undocumented (and likely unsupported) technique and still it will not take effect until the users next login.

System environment variables can be found in the registry here:
HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

CALL SET

The CALL SET syntax will expand any variables passed on the same line, which is useful if you need to set one variable based on the value of another variable. CALL SET can also evaluate a variable substring, the CALL page has more detail on this technique, though in many cases a faster to execute solution is to use Setlocal EnableDelayedExpansion.

Autoexec.bat

Any SET statement in c:\autoexec.bat will be parsed at boot time
Variables set in this way are not available to 32 bit gui programs — they won’t appear in the control panel.
They will appear at the CMD prompt.

If autoexec.bat CALLS any secondary batch files, the additional batch files will NOT be parsed at boot.
This behaviour can be useful on a dual boot PC.

Errorlevels

When CMD Command Extensions are enabled (the default):

Event Errorlevel
If the variable was successfully changed. Errorlevel = unchanged,
SET No variable found or invalid name.
SET _var=value when _var name starts with «/» and not enclosed in quotes.
SET /P Empty response from user.
1
SET /A Unbalanced parentheses 1073750988
SET /A Missing operand 1073750989
SET /A Syntax error 1073750990
SET /A Invalid number 1073750991
SET /A Number larger than 32-bits 1073750992
SET /A Division by zero 1073750993

If the Errorlevel is unchanged, typically it will be 0 but if a previous command set an errorlevel, that will be preserved (this is a bug).

# I got my mind set on you
# I got my mind set on you… — Rudy Clark (James Ray/George Harrison)

Related commands

Syntax — VarSubstring Extract part of a variable (substring).
Syntax — VarSearch Search & replace part of a variable.
Syntax — Environment Variables — List of default variables.
CALL — Evaluate environment variables.
CHOICE — Accept keyboard input to a batch file.
ENDLOCAL — End localisation of environment changes, use to return values.
EXIT — Set a specific ERRORLEVEL.
PATH — Display or set a search path for executable files.
REG — Read or Set Registry values.
SETLOCAL — Begin localisation of environment variable changes.
SETX — Set an environment variable permanently.
Parameters — get a full or partial pathname from a command line variable.
StackOverflow — Storing a Newline in a variable.
Equivalent PowerShell: Set-Variable — Set a variable and a value (set/sv).
Equivalent PowerShell: Read-Host — Prompt for user input.
Equivalent bash command (Linux): env — Display, set, or remove environment variables.


Copyright © 1999-2025 SS64.com
Some rights reserved

  • Overview
  • Part 1 – Getting Started
  • Part 2 – Variables
  • Part 3 – Return Codes
  • Part 4 – stdin, stdout, stderr
  • Part 5 – If/Then Conditionals
  • Part 6 – Loops
  • Part 7 – Functions
  • Part 8 – Parsing Input
  • Part 9 – Logging
  • Part 10 – Advanced Tricks

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.

SET foo=bar

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.

SET /A four=2+2
4

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.

C:\> SET foo=bar
C:\> ECHO %foo%
bar

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

Screenshot of the SET command

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.

Demonstration of the SETLOCAL command

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.

Demonstration of the SETLOCAL 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 09. 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.

SET myvar=%~I

  • %~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:

SETLOCAL ENABLEEXTENSIONS
SET me=%~n0
SET parent=%~dp0

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.


<< Part 1 – Getting Started


Part 3 – Return Codes >>

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Минимальный размер диска для windows xp
  • Bitlocker windows 10 взлом
  • Защита файла от удаления windows
  • Расширение aae чем открыть в windows 10
  • Картинка в окне windows