Batch-file Comments in Batch Files

I have created a shortcut for rundll32.exe powrprof.dll,SetSuspendState 0,1,0 (also tried with 0,0,0), but running the shortcut seemed to put my PC into hibernation. I could not wake up the PC using the keyboard; I had to press the power button, and the PC showed the mainboard post messages, etc.

After reading the Windows API document, I created a very simple programme with just 3 lines of typing. I have uploaded the executable I compiled to this page (click the “SleepTest.exe”), but this file could be deleted after a while (this is a free file hosting site that I just found by a quick Google search).

If you do not trust me (which is totally fine) or the file has been deleted, you can compile the code yourself, Of course. You need to add “PowrProf.lib” to the additional dependencies of the Linker.

#include "stdafx.h"
#include "windows.h" <-- Added this to make it work on Windows.
#include "PowrProf.h" <-- Added this to use the sleep function.
int main()
{ SetSuspendState(FALSE, FALSE, FALSE); <-- Added this actual call. return 0;
}

rundll32.exe powrprof.dll,SetSuspendState 0,1,0 seems to be doing the same thing, but somehow, the programme above did not put the computer into hibernation. I could wake up the PC instantly (no mainboard post messages, etc) by pressing any key on the keyboard.

Batch-file Comments in Batch Files
Download Article

Batch-file Comments in Batch Files
Download Article

If you need some extra time for a command in your batch file to execute, there are several easy ways to delay a batch file. While the well-known sleep command from older versions of Windows is not available in Windows 10 or 11, you can use the timeout, pause, ping, and choice commands to wait a specific number of seconds or simply pause until the user presses a key. This wikiHow article will teach you 5 simple ways to delay the next command in your batch file on any version of Windows.

Things You Should Know

  • The timeout command lets you pause for specific number of seconds, until a user presses a key, or indefinitely.
  • Use the pause command to delay the batch file until a user presses any key, or the choice command to give the user options to choose from.
  • You can hide on-screen messages that indicate delay to the user by adding >nul to the end of the timeout, ping, and choice commands.
  1. Image titled Delay a Batch File Step 1

    Use the timeout command to specify the delay time in seconds. By inserting the timeout command into your batch file, you can prompt the batch file to wait a specified number of seconds (or for a key press) before proceeding.[1]
    This command is available on all modern versions of windows, including Windows 10.

    • timeout /t <timeoutinseconds> [/nobreak]
    • To pause for 30 seconds and prevent the user from interrupting the pause with a keystroke, you’d enter timeout /t 30 /nobreak.
      • The user will see Waiting for 30 seconds, press CTRL+C to quit …
    • To delay 100 seconds and allow the user to interrupt the delay, you’d use timeout /t 100.
      • The user will see Waiting for 100 seconds, press a key to continue …
    • To delay indefinitely until a user enters a keystroke, use timeout /t -1.
      • The user will see Press any key to continue …
    • If you don’t want to display a message to the user during the delay, add >nul to the end of your timeout command.
  2. Advertisement

  1. Image titled Delay a Batch File Step 2

    Use the pause command to suspend the batch file until a user presses a key. This simple command doesn’t require any flags and you can place it anywhere in your script to prevent further action. When the pause command runs in the batch file, the user will see Press any key to continue . . . on a new line. When the user presses a key, the script continues.

    • You might use pause right before a section of the batch file that you might not want to process, or before providing instructions to the user to insert a disk before continuing.[2]
    • At the pause, you can stop the batch program completely by pressing Ctrl + C and then Y.
  1. Image titled Delay a Batch File Step 3

    Use ping to delay the next command in the script until a ping is complete. You can add a ping anywhere in your batch file, enter any hostname or IP address (including a nonexistent address), and specify the time in milliseconds to delay the next command. You’ll also be able to hide the output of the ping so the user won’t see what’s happening in the background.

    • ping /n 1 /w <timeout in milliseconds> localhost >nul

      • Ping has many more available flags, but for the purpose of delaying a batch file, you’ll only need to use a few. In this case, we’ll ping ourselves by using localhost as our destination.
      • To pause quietly for 10 seconds, you’d use ping /n 1 /w 10000 localhost >nul
  2. Advertisement

  1. Image titled Delay a Batch File Step 4

    Use the choice command to delay until a user selects an option from a list. You can customize the list of choices, use the default options of Y or N, or choose not to display any choices at all and simply delay your script for a specific period of time.

    • choice [/c [<choice1><choice2><…>]] [/n] [/cs] [/t <seconds> /d <choice>] [/m <text>]

      • /c <choice1><choice2><…>: Specifies the choices you’d like to create, which can include a-z, A-Z, 0-9, and ASCII characters 128-254.
      • /t <seconds>: Use this flag to specify how many seconds to wait before the default choice is selected. You can set this value to any number between 0 (which instantly selects the default choice) and 9999.
      • /d <choice>: Specifies the default choice from the list of choices created with /c.
      • /n (optional): hides the list of choices, but still allows the user to select one.
      • /m <text> (optional): displays a message before the choice list. If you don’t include this flag but don’t hide the choice list, the choices will still be displayed.
      • /cs (optional): This specifies that choices are case-sensitive, which is important if you want to assign different functions to capital and lowercase letters.
    • To create a delay with CHOICE without displaying a message or forcing the user to choose something, use rem | choice /c:AB /T:A,30 >nul. This command simply delays the batch file for 30 seconds (similar to using Timeout with no message), provides no choices to the user, and continues after the delay. You can replace 30 with any value up to 9999 (in seconds).[3]
  1. Image titled Delay a Batch File Step 5

    If you’re using Windows XP or earlier, you can use sleep to specify a wait time in seconds. This command will not work in any newer versions of Windows starting with Windows Vista, but is the easiest way to add wait time to batch files running on older systems.

    • sleep <seconds>
    • The sleep command only requires the number of seconds you want to delay the batch file. For example, to wait 30 seconds before continuing, you’d use sleep 30.
  2. Advertisement

Add New Question

  • Question

    How do I not get a message when I use timeout?

    Community Answer

    Add the >nul qualifier, like this: timeout /t 120 >nul. This causes a 2 minute delay with no output to the screen.

  • Question

    What if the sleep command doesn’t work?

    Community Answer

    If the sleep command doesn’t work, use timeout instead.

  • Question

    What if I want to wait less than one second? I can’t just use a dot or a comma.

    Community Answer

    You can use the ping command. This command, if used with a non-existent IP address, will try to talk to a non-existent computer and give up after a specified number of milliseconds. Just multiply the number of seconds by 1000, and you’re good to go.

See more answers

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

  • You can run a batch file on any Windows computer by double-clicking it, or launch it from the command prompt.

  • The “PAUSE” command is best used in situations where you’re relying on a user to trigger the next section of the batch file, while the “TIMEOUT” command is suited to situations in which you want to allow the file to run automatically.

  • The formerly used “SLEEP” command does not work on Windows Vista or later, including Windows 10 and 11.

Thanks for submitting a tip for review!

Advertisement

About This Article

Did this summary help you?

Thanks to all authors for creating a page that has been read 1,327,884 times.

Batch-file Comments in Batch Files
Загрузить PDF

Batch-file Comments in Batch Files
Загрузить PDF

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

Шаги

  1. Изображение с названием Delay a Batch File Step 1

    1

    Откройте меню «Пуск»

    Windows Start

    . Нажмите на логотип Windows в нижнем левом углу экрана.

    • Если есть готовый пакетный файл, щелкните по нему правой кнопкой мыши и в меню выберите «Изменить», чтобы открыть файл в Блокноте. Затем пропустите следующие два шага.
  2. Изображение с названием Delay a Batch File Step 2

    2

    Откройте Блокнот. Введите блокнот, чтобы найти Блокнот, а затем нажмите «Блокнот» в верхней части меню «Пуск».

  3. Изображение с названием Delay a Batch File Step 3

    3

    Создайте пакетный файл. Сначала введите команду @echo off, а затем введите другие команды своего пакетного файла.

  4. 4

    Определите, как задержать запуск пакетного файла. Для задержки пакетного файла можно использовать три основные команды:[1]

    • PAUSE — работа пакетного файла приостанавливается до тех пор, пока не будет нажата стандартная клавиша (например, пробел).
    • TIMEOUT — работа пакетного файла приостанавливается на заданное количество секунд (или до нажатия клавиши).
    • PING — работа пакетного файла приостанавливается до тех пор, пока файл не получит ответ с указанного адреса компьютера. Обычно это приводит к небольшой задержке, если пингуется рабочий адрес.
  5. Изображение с названием Delay a Batch File Step 5

    5

    Выберите место, куда ввести команду задержки. Это можно сделать в любой точке кода (но после команды «Exit», если вы ее использовали). Прокрутите вниз, найдите точку, в которой хотите приостановить работу файла, а затем введите пробел между кодом до точки задержки и кодом после этой точки.

  6. Изображение с названием Delay a Batch File Step 6

    6

    Введите команду. В зависимости от используемой команды выполните одно из следующих действий:

    • PAUSE — просто введите pause в строке.
    • TIMEOUT — введите timeout время, где вместо «время» подставьте время (количество секунд) задержки. Например, если ввести timeout 30, работа файла будет приостановлена на 30 секунд.

      • Чтобы запретить пользователям отменять задержку нажатием клавиши, введите timeout время /nobreak (где «время» — это количество секунд задержки).
    • PING — введите ping адрес, где вместо «адрес» подставьте IP-адрес пингуемого компьютера или веб-сайта.
  7. Изображение с названием Delay a Batch File Step 7

    7

    Сохраните текстовый файл как пакетный файл. Если вы еще не сохранили текстовый файл в виде пакетного файла, выполните следующие действия:

    • Нажмите «Файл» > «Сохранить как».
    • Введите имя файла, а затем введите расширение .bat (например, «Пакетный_файл.bat»).
    • Откройте меню «Тип файла» и выберите «Все файлы».
    • Выберите папку для сохранения и нажмите «Сохранить».

    Реклама

Советы

  • Чтобы запустить пакетный файл в Windows, просто дважды щелкните по нему.
  • Используйте команду «PAUSE», чтобы работа файла возобновилась вручную (когда пользователь нажжет клавишу), а команду «TIMEOUT», чтобы работа файла возобновилась автоматически.

Предупреждения

  • Команда «SLEEP» в Windows 10 не работает.
  • Пакетные файлы не работают на компьютерах Mac.

Об этой статье

Статья описывает шесть способов организации командном файле BAT/CMD задержки, задаваемой в секундах.

Хотя чаще bat файлы выполняются полностью автоматически, в некоторых случаях может понадобиться

  • Приостановка выполнения bat файла перед повтором неудачной операции, например, подключения к сетевому диску по WebDav
  • Пауза в несколько секунд после выполнения команды, чтобы пользователь мог просмотреть результат выполнения
  • Интервал между командами, каким-то образом влияющими друг на друга

Варианты задержки в bat файле

Программа PING

Запускаю PING с нужным числом запросов (примерно 1 секунда на запрос), например, на 30 секунд:

 ping localhost -n 30 >nul

Никакой информации при этом не выводится, так как вывод перенаправлен в nul..

Преимущества: работает на всех Windows компьютеров , т.к. программа PING установлена всегда и на всех версиях.

Недостатки: время задержки кратно секунде, т.е. нельзя сделать задержку менее 1 секунды, например, в 200 или 500 мс.

Программа SLEEP.EXE из Windows Resource Kit

Консольное приложение sleep.exe входит в пакет программ Windows XP Resource Kit (или Windows 2003 Resource Kit. Из краткой справки

 sleep.exe/? Usage: C:\Program Files\Windows Resource Kits\Tools\sleep.exe time-to-sleep-in-seconds C:\Program Files\Windows Resource Kits\Tools\sleep.exe [-m] time-to-sleep-in-milliseconds C:\Program Files\Windows Resource Kits\Tools\sleep.exe [-c] commited-memory ratio (1%-100%)

Поэтому для задержки в 10 секунд надо запустить

а для задержки 500 мс надо написать

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

Недостатки: SLEEP.EXE не входит в стандартный комплект Windows и может оказаться, что на целевом компьютере этого файла нет, и его надо будет распространять вместе с bat файлом.

Скрипт WSH/JScript

Создаём на JScript небольшой скрипт SLEEP.JS, использующий функцию WScript.Sleep:

var milliseconds=WScript.Arguments(0);
WScript.Sleep(milliseconds);

и вызываем его из командного файла, например, задержка 10 секунд:

cscript //nologo sleep.js 10000

или 500 мс

cscript //nologo sleep.js 500

Аналогичный скрипт можно написать на VBScript.

WScript.Sleep Wscript.Arguments(0)

Преимущества: можно задавать задержки в секундах и миллисекундах; не требуются сторонние программы.

Недостатки: требуется распространять файл скрипта вместе с bat файлом или вставлять в bat файл код для создания файла скрипта, например, так:

echo WScript.Sleep Wscript.Arguments(0) > sleep.vbs
cscript //nologo sleep.vbs 500
del sleep.vbs

Программа timeout.exe

Консольное приложение timeout.exe предустановлена в современных версиях Windows и выполняет задержку в секундах с возможностью выхода из ожидания по нажатию клавиши:

timeout /t 30

Если пауза не должна прерываться по нажатию клавиши, то надо добавить параметр /nobreak:

timeout /t 30 /nobreak

Время можно задавать только в секундах.

Пример использования программы timeout для задержки

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

Скрипт PowerShell

Функция Start-Sleep приостанавливает действие в скрипте или сеансе на указанное время, например, задержка 10 секунд:

powershell start-sleep -seconds 10

Программа nhmb

Программа nhmb имеет встроенный таймер и используется в bat файлах для создания задержки:

nhmb.exe "Ошибка подключения к серверу.\nСервер на найден" "Резервное копирование" "Question|RetryCancel" "30"

Программ nhmb выводит окно сообщения MessageBox с таймером в заголовке, чтобы пользователь мог понять, что сейчас идёт задержка перед следующей операцией и мог повлиять на ход выполнения:

Окно Message Box со значком вопроса и кнопками Повтор, Отмена в программе nhmb

Какой вариант выбрать?

В итоге, вариантов много, а что применять? На этой картинке показано тестирование всех вариантов:

Тестирование задержки в bat файлах

Ответ зависит от задачи:

Узнать больше

Файлы для скачивания

Программы

nhmb — показ всплывающего окна MessageBox с таймером обратного отсчёта

nhts – добавление даты и времени к тексту

nhcolor – выделение части текста цветом

Наши соцсети

  1. Use /WAIT to Wait for a Command to Finish Execution
  2. Use the TIMEOUT Command to Delay the Execution
  3. Use the PAUSE Command to Pause the Execution
Wait for a Command to Finish Execution in Windows Batch File

There are multiple commands and installation processes in a Batch file that usually take some time to complete. But when a Batch file is run, it does not wait for a command process to finish; it executes all commands line by line.

It is important to make those commands wait for them to finish and then execute the next commands. For a process to wait until it is finished, we use the /wait parameter with the START command.

Instead of starting a command, if there is a need to insert delays in the Batch file for some time interval, we can use commands such as TIMEOUT and PAUSE to stop the execution of the next process for a short interval of time or until a key is pressed.

This tutorial illustrates different ways to wait for a command or a program to finish before executing the next command.

Use /WAIT to Wait for a Command to Finish Execution

When we start a program in a Batch file using the START command, we can wait until the program is finished by adding /wait to the START command. Even if there are multiple commands, /wait can be used for each process to finish and move to the next one.

Also, the parameter /B is used to stay in the same process without creating a new window. The START command without the /B parameter opens the program or command in a new window.

Wait for a Command to Finish Execution

For example, we need to wait for a command to finish execution before running the next one.

@echo offecho starting first program.START /B /WAIT cmd /c "C:\Users\Aastha Gas Harda\Desktop\testfile1.bat" > output.txtecho The first program is executed successfully.START /B systeminfo >> output.txtecho All the programs are executed successfullycmd /k

wait for a command to finish

Output:

output cmd

Wait for the .exe File to Finish Execution

Another example is where we need to run a .exe file and wait until the execution is done completely.

@echo offecho starting first program.START /B /WAIT JRuler.exeecho The first program is executed successfully.START /B systeminfo >> output.txtecho All the programs are executed successfullycmd /k

wait for an exe to finish

Output:

output cmd waiting for an exe file to finish

As soon as you close the .exe file, the second program will begin execution. cmd /k in the last line is used to prevent the command prompt from exiting after execution.

If there are multiple programs, you can use /WAIT with each command to wait until the execution is finished. The START command with the /WAIT parameter doesn’t have any timeout, i.e., it does not matter how long the process will take to finish; it will wait until the process is completed.

@echo offSTART /WAIT install1.exeSTART /WAIT install2.exe

The /WAIT can only be used with the START command. We can insert a time delay for other commands by using the TIMEOUT and PAUSE commands.

Use the TIMEOUT Command to Delay the Execution

The TIMEOUT command is used to delay the execution of a command for a few seconds or minutes. It can only be used in a Batch file.

The range for the TIMEOUT command varies between -1 and 100000. If the delay is set to -1, it will act as a pause command to wait until a key is pressed.

As in the above command, we can replace the /wait by inserting the TIMEOUT command with the /t parameter. The syntax for the TIMEOUT command is given below:

Let’s take the above example and add a time delay of 30 seconds after the execution of the first program. The code for the same is shown below.

START /B JRuler.exeTIMEOUT /t START /B systeminfo >> output.txt

testfile timeout command

output timeout command

output timeout command after execution

Although, you can stop the delay by pressing the Ctrl+C which will raise the errorlevel1.

Use the PAUSE Command to Pause the Execution

The PAUSE command is used to pause the execution of a batch file until a key is pressed. It is useful if the user wants to read the output text or wait until a process is finished.

However, there is no timeout, and it will only continue until the user presses a key.

@echo offecho starting first program.START /B cmd /c "C:\Users\Aastha Gas Harda\Desktop\testfile1.bat" > output.txtecho The first program is executed successfully.PAUSESTART /B systeminfo >> output.txtecho All the programs are executed successfullycmd /k

testfile pause command

Output:

output pause command

All the methods mentioned above work fine. If you use the START command, it is recommended to use /wait instead of delay commands as the process may take longer than specified.

Как писать скрипты на BATCH? 🤔

Все на самом деле проще, чем кажется. 😉

Вывод текста на экран

@echo offecho It's my the first script on BATCH!

Вывод:

It’s my the first script on BATCH!

С первого взгляда стало понятно, чтобы вывести текст на экран нужно воспользоваться командой echo.
Но что значит первая строчка @echo off? 🤔 Первая строчка отвечает за отключения “эхо”, то есть, другими словами она отключает вывод командной строки. Представим, что вы ее не записали, и вот что у вас получится:

echo It’s my the first script on BATCH!
It’s my the first script on BATCH!

У вас отобразятся команды, которые вы записали в ваш скрипт, а потом их результат.

Комментарии, кодировка и перенос строки

Комментарии

Комментарии в коде чаще всего создаются, для описания какой-либо строчки или какого-либо блока кода.
Имеется несколько способов оставить комментарий:

@rem Смотри какой красивый комментарийrem А как тебе этот комментарий?:: И даже так можно!

Разницы не будет как вы это сделаете, комментарий не читается при исполнении скрипта – он только для вас.

Кодировка

Допустим вы захотели вывести текст в консоль, который написан кириллицей, но при выводе возникает проблема? Что это за символы?!
Для этого следует указать интернациональную кодировку UTF-8:

@echo off@rem chcp *сюда код кодировки* (65001 это UTF-8)chcp 65001echo Привет, кириллица!

Перенос строк

Если у вас в коде имеется длинная строка, которую вы хотите перенести на другую строчку, чтобы визуально это смотрелось красиво и удобно, можно воспользоваться символом ^:

@echo offchcp 65001echo У меня есть очень большой текст, который по сути бессмысленный и я придумываю этот текст на ходу, ^в прямом эфире и совершенно не важно, что здесь написано. С помощью ёлочки вверх, вы сможете перенести текст ^на следующую строку и это очень просто работает, но если вывести этот текст в консоль, он будет идти в строчку.

А что, если вы хотите вывести текст выше также, как это было и в коде? Эти ^ ёлочки не способны такого сделать, и тут можно сделать такую штуку:

@echo offchcp 65001set "n=&echo."echo Это можно сказать простая табуляция.%n%Точнее обычная переменная,^которая может спокойно перенести строчку на следующую.%n%^Переменные мы разберем в следующей главе.

Переменные

В BATCH переменные бывают глобальные 🔓 и локальные 🔒, изначально они все глобальные, а также их несколько видов.
Глобальные переменные можно использовать повсюду, в скрипте, другом bat-файле, но только в текущей сессии. Что такое текущая сессия? 🤔 Простыми словами это открытая консоль в данный момент. Давайте разбираться, но для начала посмотрим, как можно создать самую простую переменную.

set variable_name=Simple variable

Любая переменная создается с ключевого слова set, дальше можно указать тип переменной (необязательно), после обозвать её. Значения переменной указываются после символа = без пробелов. Обычная переменная может содержать только строку (string).

@echo off@rem Моя первая переменная, и сейчас я ее выведу на экран.set text=Hello, world!echo %text%

Вывод:

Hello, world!

Как вы наверное догадались, чтобы получить значение переменной, нужно обернуть название переменной в символы %.
Другой вид переменной, числовой.

С такой переменной можно проводить математические операции:

@echo off@rem Как мне сложить два числа?set /a number=2021 + 1echo New %number% year

Вывод:

New 2022 year

Также можно создать две разных переменных и сложить их воедино.

@echo offset /a number1=100set /a number2=899set /a result=number1 + number2echo %number1% + %number2% = %result%

Вывод:

100 + 899 = 999

Давайте расмотрим еще один вид переменной.

@echo offset /p input=Enter some text: echo %input%

Вход:

script запускаем файл
Enter some text: Don’t worry, smile!

Вывод:

Don’t worry, smile!

example

Такая переменная может принимать в себя данные, которые вы передадите.
Имеется еще один интересный вид переменной, она называется переменной аргумента.
Обозначается она таким образом: %1 %2 %3...

Вход:

script Something

Вывод:

Something

example

Когда мы запускаем наш bat-файл из консоли, мы можем передать любой аргумент после его названия: script Something.
script – название нашего файла, Something – наш желаемый аргумент. Если мы попытаемся передать несколько слов (аргументов) через пробел, то у нас засчитает только первое слово. То есть каждое новое слово по сути является новым аргументом.

Вход:

script Everything will be fine…

Вывод:

Everything

Этого можно избежать следующими способами:

  1. Указать больше переменных.
  2. Обернуть текст в кавычки " "
  3. Указать символ *
Способ первый:

Я хочу передать вот этот текст: Everything will be fine.... Здесь 4 слова (необязательно слова, после каждого нового пробела получается новый аргумент)

@echo offecho %1 %2 %3 %4

Вход:

script Everything will be fine…

Вывод:

Everything will be fine…

Второй способ:

В этом способе я оберну текст в кавычки " "

Вход:

script “Everything will be fine…”

Вывод:

“Everything will be fine…”

Третий способ:

Вход:

script Everything will be fine…

Вывод:

Everything will be fine…

Также на основе таких переменных можно сделать небольшой калькулятор, для этого эту переменную нужно как-бы преобразовать в числовой тип:

@echo offset /a value=%1echo %value%

Вход:

script 12+12

Вывод:

24

example

Локальные переменные

Локальные переменные задаются в блоке от setLocal до endLocal. Такими переменными нельзя воспользоваться за пределами блока, и также они недоступны в сессии, как глобальные.

@echo offset global_variable=I'm Global ElitesetLocalset local_variable=I'm... I.. nobody?...endLocal

Попробуйте запустить этот скрипт, а после прописать в консоли echo %global_variable%, получилось?
Теперь попробуйте echo %local_variable%. Мм.. нет?
Также глобальными переменными можно пользоваться в других bat-файлах. Попробуйте создать другой файлик и к примеру вывести глобальную переменную на экран.

В принципе все просто.
Практика:

  1. Попробуйте написать скрипт, который будет принимать ваше имя и возраст, после выводить его на экран.

Ваше имя: Даниил
Ваш возраст: 17
Привет, Даниил, а знаю, что тебе 17 лет!
  1. Попробуйте сделать простой калькулятор, который будет только складывать числа.

Введите первое число: 12
Введите второй число: 12
Ответ: 24

Циклы

Цикл for (по умолчанию)

Данный цикл используется для повторения файлов, пример:

@echo offfor %%i in (C:\folder\fantasy.txt C:\folder\myths.txt) do ( copy %%i C:\Users\user\Desktop
)

example
Разберем начало цикла, цикл создается с ключевого слова for, следующим можно указать вид цикла /r, /d, /f, /l (необязательно). Вид цикла используется в разных ситуациях, в которых вы хотите его применить. Дальше в этом разберемся.
Переменная в цикле начинается с двух символов %%, а после записывается само название (названием переменной должен служить 1 единственный символ). \

В ( ) записываем пути к файлам, с которыми в будущем будем осуществлять работу.
Работа осуществляется в теле цикла, чтобы туда попасть, нужно записать ключевое слово do, открыть скобки () и приступить к написанию скрипта.
В этом случае, мы просто копируем файлы (fantasy.txt, myths.txt) в новую директорию.

Цикл for /R

Данный цикл используется для перебора файлов в директории:

@echo offfor /r C:\folder %%f in (*.txt) do ( echo %%f)

example
Здесь мы уже указываем команду /r, следующим можно передать папку, которая будет считаться корневой, если не передавать директорию (C:\folder) – текущая директория будет считаться корневой. Также поиск файлов будет осуществляться и в подпапках.
%%f – является переменной. В скобках ( ), можно передать файлы, по которым будет осуществляться поиск. Их может быть несколько (*.txt *.py *.bat) или можно записать ., она будет искать все файлы в целом (в подпапках тоже).

Цикл for /D

Используется для загрузки списка папок, которые являются подпапками текущей директории:

@echo offcd C:\folderfor /d %%f in (f* n*) do ( echo %%f)

example
В данном примере мы получим список папок в директории C:\folder, которые начинаются с букв f и n. Если передать *, мы получим список всех папок находящихся в директории.

Цикл for /l

Этот цикл служит для загрузки на ряде цифр (range of numbers):

@echo offfor /l %%i in (1, 1, 10) do ( echo %%i)

example
В этом примере мы выведим цифры от 1 до 10. \

for /l %%i in (start, step, end) do ( echo %%i)
  • start: Первое значение переменной
  • step: После каждого повтора (iteration) значение переменной будет прибавлять ‘step’.
  • end: Последнее значение.

…дописывается

bat - a cat clone with wings
Build Status
license
Version info
Клон утилиты cat(1) с поддержкой выделения синтаксиса и Git

Ключевые возможности
Использование
Установка
Кастомизация
Цели и альтернативы
[English] [中文] [日本語] [한국어] [Русский]

Выделение синтаксиса

bat поддерживает выделение синтаксиса для огромного количества языков программирования и разметки:

Пример выделения синтаксиса

Интеграция с Git

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

Пример интеграции с Git

Показать непечатаемые символы

Вы можете использовать -A / --show-all флаг, чтобы показать символы, которые невозможно напечатать:

Строка с неотображемыми символами

Автоматическое разделение текста

bat умеет перенаправлять вывод в less, если вывод не помещается на экране полностью.

Объединение файлов

О… Вы также можете объединять файлы 😉. Когда
bat обнаружит неинтерактивный терминал (например, когда вы перенаправляете вывод в файл или процесс), он будет работать как утилита cat и выведет содержимое файлов как обычный текст (без подсветки синтаксиса).

Как использовать

Вывести единственный файл в терминале

Отобразить сразу несколько файлов в терминале

Читаем из stdin и определяем синтаксис автоматически (внимание: это делается по заглавной строке файла, например, #!/bin/sh)

curl -s https://sh.rustup.rs | bat”>

> curl -s https://sh.rustup.rs | bat

Прочитать из stdin с явным указанием языка

yaml2json .travis.yml | json_pp | bat -l json”>

> yaml2json .travis.yml | json_pp | bat -l json

Вывести и выделить неотображаемые символы

Использование в качестве замены cat

note.md # мгновенно создаем новый файл

bat header.md content.md footer.md > document.md

bat -n main.rs # показываем только количество строк

bat f – g # выводит ‘f’ в stdin, а потом ‘g’.”>

bat > note.md # мгновенно создаем новый файлbat header.md content.md footer.md > document.md
bat -n main.rs # показываем только количество строкbat f - g # выводит 'f' в stdin, а потом 'g'.

Интеграция с другими утилитами

find или fd

Вы можете использовать флаг -exec в find, чтобы посмотреть превью всех файлов в bat

Если вы используете fd, применяйте для этого флаг -X/--exec-batch:

ripgrep

С помощью batgrep, bat может быть использован для вывода результата запроса ripgrep

tail -f

bat может быть использован вместе с tail -f, чтобы выводить содержимое файла с подсветкой синтаксиса в реальном времени.

tail -f /var/log/pacman.log | bat --paging=never -l log

Заметьте, что мы должны отключить пэйджинг, чтобы это заработало. Мы также явно указали синтаксис (-l log), так как он не может быть автоматически определен в данном случае.

git

Вы можете использовать bat с git show, чтобы просмотреть старую версию файла с выделением синтаксиса:

git show v0.6.0:src/main.rs | bat -l rs

Обратите внимание, что выделение синтаксиса не работает в git diff на данный момент. Если вам это нужно, посмотрите delta.

xclip

Нумерация стро и отображение изменений затрудняет копирование содержимого файлов в буфер обмена.
Чтобы спроваиться с этим, используйте флаг -p/--plain или просто перенаправьте стандартный вывод в xclip:

bat обнаружит перенаправление вывода и выведет обычный текст без выделения синтаксиса.

man

bat может быть использован в виде выделения цвета для man, для этого установите переменную окружения
MANPAGER:

export MANPAGER="sh -c 'col -bx | bat -l man -p'"man 2 select

Возможно вам понадобится также установить MANROFFOPT="-c", если у вас есть проблемы с форматированием.

Если вы хотите сделать этой одной командой, вы можете использовать batman.

Обратите внимание, что синтаксис manpage разрабатывается в этом репозитории и все еще находится в разработке.

prettier / shfmt / rustfmt

Prettybat — скрипт, который форматирует код и выводит его с помощью bat.

Установка

Packaging status

Ubuntu (с помощью apt)

… и другие дистрибутивы основанные на Debian.

bat есть в репозиториях Ubuntu и
Debian и доступен начиная с Ubuntu Eoan 19.10. На Debian bat пока что доступен только с нестабильной веткой “Sid”.

Если ваша версия Ubuntu/Debian достаточно новая, вы можете установить bat так:

Если вы установили bat таким образом, то бинарный файл может быть установлен как batcat вместо bat (из-за конфликта имени с другим пакетом). Вы можете сделать симлинк или алиас bat -> batcat, чтобы предотвратить подобные проблемы и в других дистрибутивах.

mkdir -p ~/.local/bin
ln -s /usr/bin/batcat ~/.local/bin/bat

Ubuntu (С помощью самого нового .deb пакета)

… и другие дистрибутивы Linux основанные на Debian

Если пакет еще недоступен в вашем Ubuntu/Debian дистрибутиве или вы хотите установить самую последнюю версию bat, то вы можете скачать самый последний deb-пакет отсюда:
release page и установить так:

sudo dpkg -i bat_0.18.3_amd64.deb # измените архитектуру и версию

Alpine Linux

Вы можете установить bat из официальных источников:

Arch Linux

Вы можете установить bat из официального источника:

Fedora

Вы можете установить bat из официального репозитория Fedora Modular.

Gentoo Linux

Вы можете установить bat из официальных источников:

Void Linux

Вы можете установить bat с помощью xbps-install:

FreeBSD

Вы можете установить bat с помощью pkg:

или самому скомпилировать его:

cd /usr/ports/textproc/bat
make install

С помощью nix

Вы можете установить bat, используя nix package manager:

openSUSE

Вы можете установить bat с помощью zypper:

macOS

Вы можете установить bat с помощью Homebrew:

Или же установить его с помощью MacPorts:

Windows

Есть несколько способов установить bat. Как только вы установили его, посмотрите на секцию “Использование bat в Windows”.

С помощью Chocolatey

Вы можете установить bat с помощью Chocolatey:

С помощью Scoop

Вы можете установить bat с помощью scoop:

Для этого у вас должен быть установлен Visual C++ Redistributable.

Из заранее скомпилированных файлов:

Их вы можете скачать на странице релизов.

Для этого у вас должен быть установлен Visual C++ Redistributable.

С помощью Docker

Вы можете использовать Docker image, чтобы запустить bat в контейнере:

docker pull danlynn/batalias bat='docker run -it --rm -e BAT_THEME -e BAT_STYLE -e BAT_TABS -v "$(pwd):/myapp" danlynn/bat'

С помощью Ansible

Вы можете установить bat с Ansible:

# Устанавливаем роль на устройствеansible-galaxy install aeimer.install_bat

---# Playbook для установки bat- host: all roles: - aeimer.install_bat
  • Ansible Galaxy
  • GitHub

Этот способ должен сработать со следующими дистрибутивами:

  • Debian/Ubuntu
  • ARM (например Raspberry PI)
  • Arch Linux
  • Void Linux
  • FreeBSD
  • macOS

Из скомпилированных файлов

Перейдите на страницу релизов для
скомпилированных файлов bat для различных платформ. Бинарные файлы со статической связкой так же доступны: выбирайте архив с musl в имени.

Из исходников

Если вы желаете установить bat из исходников, вам понадобится Rust 1.64.0 или выше. После этого используйте cargo, чтобы все скомпилировать:

cargo install --locked bat

Кастомизация

Темы для выделения текста

Используйте bat --list-themes, чтобы вывести список всех доступных тем. Для выбора темы TwoDark используйте bat с флагом
--theme=TwoDark или выставьте переменную окружения BAT_THEME в TwoDark. Используйте export BAT_THEME="TwoDark" в конфигурационном файле вашей оболочки, чтобы изменить ее навсегда. Или же используйте конфигурационный файл bat.

Если вы хотите просто просмотреть темы, используйте следующую команду (для этого вам понадобится fzf):

bat --list-themes | fzf --preview="bat --theme={} --color=always /путь/к/файлу"

bat отлично смотрится на темном фоне. Однако если ваш терминал использует светлую тему, то такие темы как GitHub или OneHalfLight будут смотреться куда лучше!
Вы также можете использовать новую тему, для этого перейдите в раздел добавления тем.

Изменение внешнего вывода

Вы можете использовать флаг --style, чтобы изменять внешний вид вывода в bat.
Например, вы можете использовать --style=numbers,changes, чтобы показать только количество строк и изменений в Git. Установите переменную окружения BAT_STYLE чтобы изменить это навсегда, или используйте конфиг файл bat.

Добавление новых синтаксисов

bat использует syntect для выделения синтаксиса. syntect может читать
файл .sublime-syntax
и темы. Чтобы добавить новый синтаксис, сделайте следующее:

Создайте каталог с синтаксисом:

mkdir -p "$(bat --config-dir)/syntaxes"cd "$(bat --config-dir)/syntaxes"# Разместите файлы '.sublime-syntax'# в каталоге (или субкаталогах), например:git clone https://github.com/tellnobody1/sublime-purescript-syntax

Теперь используйте следующую команду, чтобы превратить эти файлы в бинарный кеш:

Теперь вы можете использовать bat --list-languages, чтобы проверить, доступны ли новые языки.

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

Добавление новых тем

Это работает похожим образом, так же как и добавление новых тем выделения синтаксиса

Во-первых, создайте каталог с новыми темами для синтаксиса:

mkdir -p "$(bat --config-dir)/themes"cd "$(bat --config-dir)/themes"# Загрузите тему в формате '.tmTheme':git clone https://github.com/greggb/sublime-snazzy# Обновите кешbat cache --build

Теперь используйте bat --list-themes, чтобы проверить доступность новых тем.

Использование другого пейджера.

bat использует пейджер, указанный в переменной окружения PAGER. Если она не задана, то используется less.
Если вы желаете использовать другой пейджер, вы можете либо изменить переменную PAGER, либо BAT_PAGER чтобы перезаписать то, что указано в PAGER.

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

export BAT_PAGER="less -RF"

Так же вы можете использовать файл конфигурации bat (флаг --pager).

Внимание: По умолчанию пейджером являетсяless (без каких-либо аргументов),
bat задаст следующие флаги для пейджера:
-R/--RAW-CONTROL-CHARS,
-F/--quit-if-one-screen и -X/--no-init. Последний флаг(-X) используется только для less, чья версия раньше 530.

Флаг -R нужен чтобы корректно воспроизвести ANSI цвета. Второй флаг (-F) говорит
less чтобы тот сразу же завершился, если размер вывода меньше чем вертикальный размер терминала.
Это удобно для небольших файлов, так как вам не надо каждый раз нажимать q, чтобы выйти из пейджера. Третий флаг (-X) нужен для того, чтобы исправить баг с --quit-if-one-screen в старых версиях less. К сожалению, это блокирует возможность использования колеса мышки.

Если вы хотите все же его включить, вы можете добавить флаг -R.
Для less новее чем 530 оно должно работать из коробки.

Темная тема

Если вы используете темный режим в macOS, возможно вы захотите чтобы bat использовал другую тему, основанную на теме вашей ОС. Следующий сниппет использует тему default, когда у вас включен темный режим, и тему GitHub, когда включен светлый.

/dev/null && echo default || echo GitHub)"”>

alias cat="bat --theme=\$(defaults read -globalDomain AppleInterfaceStyle &> /dev/null && echo default || echo GitHub)"

Файл конфигурации

bat также может быть кастомизирован с помощью файла конфигурации. Его местоположение зависит от вашей ОС: чтобы посмотреть его путь, введите

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

export BAT_CONFIG_PATH="/path/to/bat.conf"

Файл конфигурации «по умолчанию» может быть создан с помощью флага --generate-config-file.

bat --generate-config-file

Формат

Файл конфигурации – это всего лишь набор аргументов. Введите bat --help, чтобы просмотреть список всех возможных флагов и аргументов. Также вы можете закомментировать строку с помощью #.

Пример файла конфигурации:

# Установить тему "TwoDark"--theme="TwoDark"# Показывать количество строк, изменений в Git и заголовок файла--style="numbers,changes,header"# Использовать курсив (поддерживается не всеми терминалами)--italic-text=always# Использовать синтаксис C++ для всех Arduino .ino файлов--map-syntax "*.ino:C++"# Использовать синтаксик Git Ignore для всех файлов .ignore--map-syntax ".ignore:Git Ignore"

Использование bat в Windows

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

Пейджинг

Windows поддерживает только очень простой пейджер more. Вы можете скачать установщик для less с его сайта или через Chocolatey. Чтобы его использовать, скопируйте исполняемый файл в ваш PATH или используйте переменную окружения. Пакет из Chocolatey установит все автоматически.

Цвета

Windows 10 поддерживает цвета и в conhost.exe (Command Prompt), и в PowerShell начиная с версии Windows
[v1511](https://ru.wikipedia.org/wiki/Windows_10#Обновления и поддержка), так же как и в bash. На ранних версиях Windows вы можете использовать
Cmder, в котором есть ConEmu.

Внимание: Версия less в Git и MSYS2 воспроизводит цвета некорректно. Если у вас нет других пейджеров, мы можете отключить использование пейджеров с помощью флага --paging=never
или установить BAT_PAGER равным пустой строке.

Cygwin

Из коробки bat не поддерживает пути в стиле Unix (/cygdrive/*). Когда указан абсолютный путь cygwin, bat выдаст следующую ошибку: The system cannot find the path specified. (os error 3)

Она может быть решена добавлением следующей функции в .bash_profile:

bat() { local index local args=("$@") for index in $(seq 0 ${#args[@]}) ; do case "${args[index]}" in -*) continue;; *) [ -e "${args[index]}" ] && args[index]="$(cygpath --windows "${args[index]}")";; esac done command bat "${args[@]}"}

Проблемы и их решение

Терминалы и цвета

bat поддерживает терминалы с и без поддержки truecolor. Однако подсветка синтаксиса не оптимизирована для терминалов с 8-битными цветами, и рекомендуется использовать терминалы с поддержкой 24-битных цветов (terminator, konsole, iTerm2, …).
Смотрите эту статью для полного списка терминалов.

Удостовертесь, что переменная COLORTERM равна truecolor или
24bit. Иначе bat не сможет определить поддержку 24-битных цветов (и будет использовать 8-битные).

Текст и номера строк плохо видны

Используйте другую тему (bat --list-themes выведет список всех установленных тем). Темы OneHalfDark и
OneHalfLight имеют более яркие номера строк и тексты.

Кодировки файлов

bat поддерживает UTF-8 и UTF-16. Файлы в других кодировках, возможно, придётся перекодировать, так как кодировка может быть распознана неверно. Используйте iconv.
Пример: у вас есть PHP файл в кодировке Latin-1 (ISO-8859-1):

iconv -f ISO-8859-1 -t UTF-8 my-file.php | bat

Внимание: вам может понадобится флаг -l/--language, если bat не сможет автоматически определить синтаксис.

Разработка

# Рекурсивно клонирует все модулиgit clone --recursive https://github.com/sharkdp/bat# Компиляции в режиме разработкиcd bat
cargo build --bins# Запуск тестовcargo test# Установка (релизная версия)cargo install --locked# Компилирование исполняего файла bat с другим синтаксисом и темамиbash assets/create.sh
cargo install --locked --force

Разработчики

  • sharkdp
  • eth-p

Цели и альтернативы

Цели проекта bat:

  • Красивая и продвинутая подсветка синтаксиса.
  • Интеграция с Git.
  • Полноценная замена cat.
  • Дружелюбный интерфейс и аргументы.

Есть очень много альтернатив bat. Смотрите этот документ для сравнения.

Лицензия

Copyright (c) 2018-2021 Разработчики bat.

bat распостраняется под лицензями MIT License и Apache License 2.0 (на выбор пользователя).

Смотрите LICENSE-APACHE и LICENSE-MIT для более подробного ознакомления.

In Windows, the batch file is a file that stores commands in a serial order. The command line interpreter takes the file as an input and executes in the same order. A batch file is simply a text file saved with the .bat file extension. It can be written using Notepad or any other text editor. A simple batch file will be:

// When echo is turned off, the command prompt doesn't appear in the Command Prompt window.
ECHO OFF
// The following command writes GeeksforGeeks to the console.
ECHO GeeksforGeeks
// The following command suspends the processing of a batch program and displays the prompt.
PAUSE

After saving it with a .bat extension. Double click it to run the file. It prints shows:

Batch-file Comments in Batch Files 

In the above script, ECHO off cleans up the console by hiding the commands from being printed at the prompt, ECHO prints the text “GeeksforGeeks” to the screen, and then waits for the user to press a key so the program can be ceased. Some basic commands of batch file:

  • ECHO – Prints out the input string. It can be ON or OFF, for ECHO to turn the echoing feature on or off. If ECHO is ON, the command prompt will display the command it is executing.
  • CLS – Clears the command prompt screen.
  • TITLE –  Changes the title text displayed on top of prompt window.
  • EXIT – To exit the Command Prompt.
  • PAUSE – Used to stop the execution of a Windows batch file.
  • :: – Add a comment in the batch file.
  • COPY – Copy a file or files.

Types of “batch” files in Windows:

  1. INI (*.ini) – Initialization file. These set the default variables in the system and programs.
  2. CFG (*.cfg) – These are the configuration files.
  3. SYS (*.sys) – System files, can sometimes be edited, mostly compiled machine code in new versions.
  4. COM (*.com) – Command files. These are the executable files for all the DOS commands. In early versions there was a separate file for each command. Now, most are inside COMMAND.COM.
  5. CMD (*.cmd) – These were the batch files used in NT operating systems.

Lets take another example, Suppose we need to list down all the files/directory names inside a particular directory and save it to a text file, so batch script for it will be,

@ECHO OFF
// A comment line can be added to the batch file with the REM command.
REM This is a comment line.
REM Listing all the files in the directory Program files
DIR"C:\Program Files" > C:\geeks_list.txt
ECHO "Done!"

Now when we run this batch script, it will create a file name geeks_list.txt in your C:\ directory, displaying all the files/folder names in C:\Program Files. Another useful batch script that can be written to diagnose your network and check performance of it:

// This batch file checks for network connection problems.
ECHO OFF
// View network connection details
IPCONFIG /all
// Check if geeksforgeeks.com is reachable
PING geeksforgeeks.com
// Run a traceroute to check the route to geeksforgeeks.com
TRACERT geeksforgeeks.com
PAUSE

This script displays:

Batch-file Comments in Batch Files 

This script gives information about the current network and some network packet information. ipconfig /all helps to view the network information and ‘ping’ & ‘tracert’ to get each packet info. Learn about ping and traceroute here.

Last Updated :
29 Sep, 2022

Like Article

Save Article

I love shell scripting – it’s the duct tape of programming to me. Low cost, high benefit. And it feels like art, where one can learn to do increasingly complex tasks with greater simplicity.

Sadly, I feel like it’s a developer skill on the decline. Maybe new developers feel it’s “not real programming”. Perhaps the growing dominance of Java as the lingua franca of academic comp sci courses has made shell scripting less relevant in university settings.

True, shell scripting feel a bit “vocational”, maybe even a bit unsexy compared to Python/Ruby/LISP/blah/blah/blah. Nevertheless, it’s a skill that becomes invaluable as you gain seniority and start doing more DevOps in you day job, or if you want to do some high-speed, low drag stuff to tailor your development environment like this.

Why Windows?

This series will share some of the tips and tricks I’ve picked up through the years of working with Windows professionally. I’ll be the first to admit the Unix shells of the world are far superior to the Windows command prompt (or even Windows PowerShell). Windows is a fact of life for most professionals writing code for coporate customers; this series aims to make life with Windows a little easier.

Why DOS-style Batch Files?

This series will share some conventions I picked up along the way for scripting in Windows via command prompt batch files. The Windows PowerShell is definitely sweet, but, I still like batch files for their portability and low friction. The Windows command line is very stable – no worrying about the PowerShell interpreter path, which version of PowerShell the server is running, etc.

Series Parts

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

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.

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.

Command Line Arguments to Your Script

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

Some Final Polish

I always include these commands at the top of my batch scripts:

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


<< Part 1 – Getting Started


Part 3 – Return Codes >>

Introduction

Comments are used to show information in a batch script.

Syntax

  •  Comments. You can also use |>< ,etc.
REM This is a comment
  • REM is the official comment command.
::This is a label that acts as a comment

The double-colon :: comment shown above is not documented as being a comment command, but it is a special case of a label that acts as a comment.

The cmd shell will try to execute the second line even if it is formatted as a label (and this causes an error):

(
echo This example will fail
:: some comment
)

It is also possible to use variables as comments. This can be useful to conditionally prevent commands being executed:

@echo off
setlocal
if /i "%~1"=="update" (set _skip=) Else (set _skip=REM)
%_skip% copy update.dat
%_skip% echo Update applied
... 

When using the above code snippet in a batch file the lines beginning with %_skip% are only executed if the batch file is called with update as a parameter.

@echo off
goto :start
A multi-line comment block can go here.
It can also include special characters such as | >
:start

Since the parser never sees the lines between the goto :start statement and :start label it can contain arbitrary text (including control characters without the need to escape them) and the parser will not throw an error.

@echo off
echo This is a test &::This is a comment
echo This is another test &rem This is another comment
pause

A curiosity: SET command allows limited inline comments without &rem:

set "varname=varvalue" limited inline comment here
  • syntax with double quotes set "varname=varvalue" or set "varname=",
  • an inline comment may not contain any double quote,
  • any cmd poisonous characters | < > & must be properly escaped as ^| ^< ^> ^&,
  • parentheses ( ) must be properly escaped as ^( ^) within a bracketed code block.
<!-- : Comment

This works with both batch script and WSF. The closing tag(-->), only works in WSF.

:/>  Общий доступ для интернета