Windows batch script variables

Дисклеймер

Мне 12 и я сам в этой теме плохо шарю, т.к. инфы в инете мало. Пж, без хейта.

Что такое батники и с чем их едят

Пакетный файл или в простонародье батник — это файл, который запускает командную сроку или сокращенно cmd, которая построчно интерпретирует команды, записанные в нем. Подробнее смотрите на https://ru.wikipedia.org/wiki/Пакетный_файл.

Первая программа и основные команды

Чтобы сделать батник, нужно сначала создать текстовый файл с именем test и изменить расширение c .txt на .bat. О том, как можно это сделать, читайте здесь: https://remontka.pro/file-extensions. У вас должен появиться файл с такой иконкой:

test.bat

Нажимаем на него ПРАВОЙ кнопкой мыши. Должно появиться диалоговое окно. Нажмем «Открыть». Должен открыться блокнот, пишем:

@echo off
echo Hello world!
pause

В 1-ой сроке («@echo off») префикс ‘@ ‘ означает, что команда не будет выведена на экран(попробуйте его убрать :-) ), сама же команда (echo) выводит текст следующий за ней(см. строку 2), НО, если подать строку «off», все последующие команды будут действовать так, как будто перед ними стоит префикс ‘@’, «echo on», соответственно, выключает этот режим. Чтобы вывести символ «%», его нужно дублировать, потом поймете почему :-), для вывода пустой строки поставьте «.» после «echo»
В 3-ей строке команда выводит строку «press any key to continue . . .» (если у вас русский язык — «Для продолжения нажмите любую клавишу . . .») и останавливает программу до нажатия любой клавиши.

Наводим красоту

Команда «rem»

не эта :)

не эта :)

не делает ничего и служит комментарием к коду

rem Это самая лучшая прога в мире!!!!!

Код включает русские символы и другие из ascii(например: «╬▓☼», можно скопировать с http://pascalguru.ru/psevdograf.html), иначе ascii символы превратятся в кракозябры:

chcp 65001

Следующий код код работает, как команда «pause», но ничего не выводит на экран и не реагирует на нажатие клавиш(я потом объясню, как это работает).

:m
goto m

А этот — меняет заголовок окна на «name»

Заголовок окна

Заголовок окна
title name

Эта команда меняет цвет фона и текста, вместо a и b можно поставить любые шестнадцатеричные цифры(команда не сработает если a = b) см. таблицу ниже. Запись c одной буквой «а» аналогично записи «0a»

color ab
Таблица

Таблица

Эта — досрочно завершает программу

exit

Переменные

Создать переменную можно с помощью команды set, синтаксис объявления следующий: P.S. это не совсем переменные, это скорее макросы (для тех к кто не знает C/C++ это именованный кусочек кода, имя которого заменяется на этот кусочек кода)

set a=Hello world

Если после «set» добавить флаг «/a» то:

  1. Переменной задастся значение выражения, а не его текст, например:

    set a=2+2
    > 2+2
    set /a a=2+2
    > 4
  2. Переменной можно присвоить ТОЛЬКО числовое значение

Чтобы обратиться к переменной, нужно окружить ее символами «%» (так %name%), пример кода:

set /a a=%b%+%b%
echo %a%

Подробнее о переменных

Если добавить флаг «/p», то выводиться значение после символа «=», а переменной задается введенное значение(запустите этот код:)

@echo off
set /p a=Enter str
echo %a%
pause

следующий код вырезает строку от символа номер «a» до символа номер «b» НЕ включительно(счет идет с нуля, отрицательные числа — счет с конца от единицы). Если аргумент один, то он присваивается числу «b», а «a» = 0

%str:~a,b%

следующий заменяет подстроки «a» в строке на строки «b»:

%str:a=b%

Циклы и условия

Цикл можно создать с помощью команды «for», синтаксис следующий:

for %%i in (a b c) do (
		cmd
)

или такой

for %%i in (a b c) do cmd

(a b c) это список (не обязательно из 3-х элементов) и переменная %%i (нужно ставить символ после процентов, а не между) по очереди проходит по значениям в списке

Если добавить флаг «/l», то переменная в первый раз будет равна «a». К ней каждый раз будет прибавляться «b», пока она не станет больше «c»(тут размер ДОЛЖЕН равняться 3)

запустите этот код, тут все наглядно

@echo off
chcp 65001
echo Начало
for /l %%i in (1 1 10) do echo %%i
echo Конец
pause

Команда if выполняет код, если условие верно (или если поставить not после if, когда НЕ верно), вот операторы сравнения:

P.S. строки нужно брать в кавычки «%str%»==»Hello»

equ(==)

=

neq

lss

<

leq

gtr

>

geq

пример кода:

@echo off
set /p a=Enter number
if a gtr 0 echo positive else\
if a equ 0 echo 0 else echo negative
pause

в 3-ей строке, если «a» > 0 выводиться «положительный»(на английском :-) ), если равен — 0,в 4-ой если меньше — «отрицательный»

символ «\» означает, что команда продолжается на следующей строке

Метки

Создадите файл start.bat в той же папке, где и test.bat, напишите в нем:

test.bat 2 2

Мы запустили батник, НО подали в него аргументы 2 и 2. Чтобы к ним обратиться, нужно написать %n, где «n» — номер аргумента, считая от одного(не от нуля), вот код, считающий сумму первого и второго аргумента (их может быть от нуля до 9-и):

@echo off
set /a res=%1+%2
echo res
pause

Метка — это именованное место в коде, она создается с помощью команды «:name»

А этот переходит на метку :m и продолжает выполнение, начиная с нее

rem куча кода
:m
rem куча кода
goto m
rem куча кода

И в завершение статьи, хочу сказать о команде call. Она превращает в последующей команде «%%» в «%», а переменные — на их значения. Пример использования:

call echo %%str:~%a%,%b%%%

  • 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 >>

Hello, future programmers! Today, we’re diving into the exciting world of Batch Script variables. As your friendly neighborhood computer teacher, I’m here to guide you through this journey, step by step. Don’t worry if you’ve never programmed before – we’ll start from the very beginning and work our way up. So, grab a cup of your favorite beverage, and let’s get started!

Batch Script - Variables

What Are Variables?

Before we jump into the specifics of Batch Script variables, let’s understand what variables are in general. Think of variables as containers that hold information. Just like you might use a box to store your favorite toys, we use variables to store data in our programs.

Command Line Arguments

Let’s start with something fun – command line arguments! These are like little messages we can send to our Batch Script when we run it.

Example 1: Hello, Name!

@echo off
echo Hello, %1!

Save this as greet.bat and run it like this: greet.bat John

What happens here? The %1 in our script is replaced by the first argument we provide (in this case, «John»). So, the script will say «Hello, John!»

Example 2: Multiple Arguments

@echo off
echo First argument: %1
echo Second argument: %2
echo Third argument: %3

Save this as args.bat and run it like this: args.bat apple banana cherry

This script will display:

First argument: apple
Second argument: banana
Third argument: cherry

Each %n (where n is a number) represents an argument in the order they’re provided.

Set Command

The set command is our magic wand for creating variables in Batch Script. Let’s see how it works!

Example 3: Creating a Simple Variable

@echo off
set message=Hello, World!
echo %message%

When you run this script, it will display «Hello, World!» The set command creates a variable named message and assigns it the value «Hello, World!». We then use %message% to display its contents.

Example 4: User Input

@echo off
set /p name=What's your name? 
echo Nice to meet you, %name%!

The /p flag with set allows us to prompt the user for input. This script asks for the user’s name and then greets them.

Working with Numeric Values

Batch Script can handle numbers too! Let’s explore some mathematical operations.

Example 5: Basic Arithmetic

@echo off
set /a result=5+3
echo 5 + 3 = %result%

set /a result=10-4
echo 10 - 4 = %result%

set /a result=6*2
echo 6 * 2 = %result%

set /a result=15/3
echo 15 / 3 = %result%

The /a flag tells set that we’re dealing with arithmetic. This script demonstrates addition, subtraction, multiplication, and division.

Example 6: More Complex Calculations

@echo off
set /a result=(10+5)*2
echo (10 + 5) * 2 = %result%

set /a result=20%%3
echo 20 %% 3 = %result%

Here, we’re using parentheses for order of operations and %% for modulus (remainder after division).

Local vs Global Variables

In Batch Script, variables are usually global, meaning they’re accessible throughout the entire script. However, we can create local variables within blocks of code.

Example 7: Global vs Local Variables

@echo off
set global_var=I'm global!

setlocal
set local_var=I'm local!
echo Inside block: %local_var%
echo Global variable: %global_var%
endlocal

echo Outside block: %local_var%
echo Global variable: %global_var%

This script demonstrates how local variables are only accessible within their block (between setlocal and endlocal), while global variables can be accessed anywhere.

Working with Environment Variables

Environment variables are special variables that Windows uses to store system-wide information.

Example 8: Displaying Environment Variables

@echo off
echo Your username is: %USERNAME%
echo Your home directory is: %USERPROFILE%
echo The current date is: %DATE%
echo The current time is: %TIME%

This script displays some common environment variables. Windows provides many of these for us to use.

Example 9: Creating Custom Environment Variables

@echo off
setx MY_CUSTOM_VAR "Hello from the environment!"
echo %MY_CUSTOM_VAR%

The setx command creates a permanent environment variable. Note that you might need to open a new command prompt to see the changes.

Conclusion

Congratulations! You’ve just taken your first steps into the world of Batch Script variables. Remember, practice makes perfect, so don’t be afraid to experiment with these examples and create your own scripts.

Here’s a quick reference table of the commands we’ve learned:

Command Description
%n Access command line arguments
set Create or modify variables
set /p Create variables with user input
set /a Perform arithmetic operations
setlocal Start a local variable block
endlocal End a local variable block
setx Create environment variables

Happy scripting, and may your variables always be well-defined!

Credits: Image by storyset

декларация

Чтобы создать простую переменную и присвоить ее значению или строке, используйте команду 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

When a Command Window is opened, it will start a session. Such session will finish upon closing the Command Window. During a session you can execute one or more batch files. The variables created in the previous file can be visited in the following file. Such variables are called global variables. However, you can create a local variable. The local variable only exists within the file of defining it or in a section of that file.

Example of Local Variables

Local variables are declared in a block, starting with setlocal and ending with endlocal.

localVariable.bat

@echo off
set global1=I am a global variable 1

setlocal
  set local1=I am a local variable 1
  set local2=I am a local variable 2
  echo ----- In Local Block! -----
  echo local1= %local1%
  echo local2= %local2%
endlocal

echo  ..
echo ----- Out of Local Block! -----
echo global1= %global1%
echo local1= %local1%
echo local2= %local2%
pause

Example of Global Variables:

Variables, declared in the Batch file, and not located in the setlocal .. endlocal block, will be global variables. They can be used in other files in the same session.

In this example, we have two files such as batchFile1.bat and batchFile2.bat. The MY_ENVIRONMENT variable is defined in file 1, and which is used in file 2.

batchFile1.bat

@echo off
set MY_ENVIRONMENT=C:/Programs/Abc;C:/Test/Abc

batchFile2.bat

@echo off
echo In batchFile2.bat 
echo MY_ENVIRONMENT=%MY_ENVIRONMENT%

Open CMD, and CD to the folder containing the batchFile1.bat, batchFile2.bat files and run these files respectively.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как сделать скриншот на компьютере windows 10 про
  • Openssh windows права доступа
  • Восстановить гугл хром бесплатно для windows 7
  • Acer aspire v5 572g drivers windows 8
  • Как обновить cmake windows