How to create a text file with a bat extension. How to create a file with a bat extension? What are these files for?

A BAT file is a program code saved with the extension .bat or .CMD as you like.

The possibilities of bat files are almost limitless, but as a rule, programmers use these extensions in simple and routine matters.

Using a bat file, you can open files on your computer, copy, move and delete files with or without a mask, run scripts from third-party programs, and open a browser with the desired url. I often use such files to open ftp folders on a remote server.

How to create a bat file

Creating baht files couldn't be easier. Open a regular text editor and save it with the .bat extension.

You can also use the advanced program “notepad++”

Here is a sample code to write a bat file:

explorer.exe "C:\Program Files"

This code will open the “program files” folder on the C:\ drive

Writing .bat files requires special care from the computer user. Since batch files can delete entire directories, format a computer partition

Here is a code example - formatting the F:\ partition

@echo off
format F /q /autotest

Example bat code - Create 100 folders:

@echo off
for /l %%i in (1,1,100) do mkdir "dir %%i"

You can make a bat and (Virus) a harmful program script: For example, the code below will delete important exe files.

@echo off
do del "c:\windows\exploer.exe"
do del "c:\windows\mspoint.exe"
do del "c:\windows\notepad.exe"

Command to create a folder with a bat file

The code below will create 3 folders in the location where the file itself is located. Also, the first folder created will contain another subfolder. Since the folder names are written in Cyrillic, we add the encoding line chcp 1251. Such a file cannot be written with a regular notepad, since it is not possible to change the encoding of Russian letters. Use notepad++.

chcp 1251
MD .\folder_article\base\
MD .\directory\
MD .\storage\

Download Bat file

- the file creates 3 folders

Example bat code how to open a folder

explorer.exe "C:\Users\Administrator\Desktop\photo\"

How to open bat format?

Just like creating .bat files in a text editor, they can be opened with the same notepad, wordpad, or notepad++.

The only thing to remember when opening a bat file is that when you double-click on the file, it will launch the program. That is, to open it for editing, move the cursor over the file being edited and right-click to open the context menu where select open with notepad++

Also, if you click on just open in the context menu, you will also launch the execution of the bat file.

There is another way: Open the text editor Notepad and drag your edited file into it.

Important: Users often confuse the concepts of files with the .bat extension and the “The Bat” mail client for sending and receiving mail documents.

Basic Bat File Operators

@ All commands executed by bat are displayed on the screen, to remove unnecessary things, a “dog” is placed in front of the command. Often used with @echo off.
set Sets variables. For example, setper=c:\windows here per assigns the path. You can write a cumbersome value to a variable and specify it in the script, which makes the code more compact. If its content changes, then you will not have to change the values ​​everywhere where this variable is provided.
:: One of two methods for commenting in a bat file without displaying this line on the screen.
:LABEL When you add a colon to a word, a label is created that allows you to jump to different sections of the body file. A label can have a different name, LABEL is an example.
CALL Bat command calling one batch file within another. All parameters described in one of the files can be passed to each other.
CHOICE Select command.
CLS Clears the shell contents that are displayed above the CLS.
ECHO Displays a message on the screen. For example, “ECHO How are you!” will display “How are you!” If you don't use @ECHO off at the beginning of the batch file, then you will see the path to the bat file and two messages, which is unnecessary. You can create an empty line by typing ECHO. with a period at the end.
EXIT Ends the current batch script.
GOTO LABEL Used to jump to a specific label, in this case LABEL, and execute the script after it.
IF As in the bat programming languages, the if command represents the fulfillment of a condition, depending on which the script will go along one path or another. Please refer to the help for the syntax.
for A loop used to organize the same actions over and over again.
PAUSE If you need to see the output of a script and it runs and the window closes quickly, then use PAUSE. It will allow you to view the result and complete the script by pressing any button.
R.E.M. Second way to comment. Unlike:: is printed on the screen if there is no @ECHO off construct.
SHIFT Changes the position of batch parameters in the bat file.
START Launches programs, windows, etc. Has many attributes.

For a more detailed description of the bat file code, read the Windows Help

Bat files are text documents that contain a list of sequentially executed commands (instructions). They can be so simple that the average user can use them. In today’s topic, we’ll look at what a batch file is, how to create a bat file in Windows 7, 8, and also consider an example batch file.

System administrators (advanced users) are well aware of the usefulness of bat files, but ordinary users are not familiar with them, they are intimidated by the structure of the code and running this script. This is unfortunate because many people shy away from using a powerful tool to perform routine and repetitive tasks. Bat files can be complex, requiring professional programming skills, or simple.

A body file contains one or more lines of commands that are executed sequentially. Bat files have an extension (bat or cmd) and are executed through the command interpreter interface. All commands can be entered into cmd, but each time writing the code is a chore, so it’s easier to create a bat file.

Creating a bat file

To create a batch file, you will need a text editor (notepad, notepad++) and . See the approximate algorithm below.

1. Create a text document with the extension txt. Right-click on an empty area of ​​File Explorer or other location. Point to "create", then select "text document" from the submenu. Give it a name, for example, batnik.

2. Download notepad++ then install it. Open batnik.txt in notepad++, select “encodings”, hover over “encodings”, “Cyrillic”, click on OEM 866. Do this step if you are using the output of Russian words (explanations) in the script, otherwise you will see crappy language ( not valid characters). Next, write down the commands. For example, copy this text:

@echo off
echo Hello – bat file test
pause
dir c:\windows
pause

4. Double-click to run batnik.bat to execute a sequence of commands. After the bat file is executed, it will automatically close.

You can also launch notepad, press Win + R, enter notepad in the line and click Enter. After entering the code, click “file” and then “save as”. In the window, specify the save path, file name with the bat extension and click “save”. Do the same with notepad++ to change the encoding (step 2) if you use Russian characters.

Example bat file

Now let's look at creating a bat file in Windows 7, 8, which provides information about the network, checks the Internet connection and clearly shows the action of batch files. Create a bat file and write these lines.

ECHO OFF
:: cleaner.
ECHO Information about connections.
:: displays the text on the screen that comes after the service word ECHO.
IPCONFIG /ALL
:: Prints information about all network connections.
PAUSE
:: Pauses the script so you can view network information.
PING yandex.ru
:: Ping, checking the presence (absence) of an Internet connection
ECHO Operation completed. Press enter!
:: Displays the words after ECHO, which indicate the execution of PING.
PAUSE
:: This last command is written in order to see connection information. If it were not there, then the batch script would stop and the window would close.

In fact, there are a huge number of examples of baht files for training and downloading on the Internet. You just need to study the syntax and commands to create your own batch file to suit your needs. I hope you understand why batch files are needed, and how to create a bat file in Windows 7.8.

A batch (bat) file is a file type that supports text, has a .bat extension, and includes line-by-line statements for the cmd.exe command line.

This file type is a useful tool for automating monotonous file operations - copying, deleting, etc., as well as launching various applications and performing other operations in the OS.

For example, if you need to run the ipconfig/flushdns DOS command to flush the DNS resolver cache, you can do this by running cmd.exe. However, if the procedure needs to be repeated many times, it is better to do this by launching a previously created bat file.

When creating a bat file, you may need to enable display of file extensions. For this:


For this:

  1. Open Notepad by typing the word notepad in the search bar of the taskbar (the magnifying glass image at the bottom left) and clicking on the icon that pops up.

  2. Enter the commands ipconfig /flushdns and pause in notepad.

    Reference! Using the “pause” operator does not allow the DOS screen to close after executing the bat file, so that the user can see the response from the cmd interpreter.

  3. In the notepad window, click “File” - “Save As”.

  4. In the “Save As” window, click on the left where to place the file, write the name of the file to be created and specify the .bat extension (through a dot) (1), selecting “File type” - “All files” (2). Then click “Save” (3).

  5. Double-click on the saved file. In some situations, you may need to run bat as an administrator. To do this, right-click on it and select “Run as administrator.”

The result of executing the bat file will be displayed in the DOS window.

In this case, the contents of the DNS name resolution cache were successfully cleared, correcting web rendering problems and other DNS issues. The system is prompted to press any key to close the window.

If you want to find out in more detail and also consider the creation instructions, you can read an article about it on our portal.

Basic bat file operators:

  • ECHO: displays text in a DOS window;
  • ECHO OFF: cancels the display of command text in the DOS window, showing a hint and the executed result;
  • @ECHO OFF: cancels the display of command text and hints, showing the completed result;
  • XCOPY: used to copy directories and files with additional parameters;
  • START: launches the executable file.exe with its standard application, opens the directory;
  • FOR/IN/DO: used to specify files;
  • MKDIR: creates directories;
  • REM: to enter a comment line in the program;
  • RMDIR: for deleting directories;
  • DEL: to delete files;
  • COPY: to copy files;
  • TITLE: Edit the window title.

The use of some of the listed commands is shown in the example below. It should be noted that the @echo off command hides the path of the command being executed as displayed by cmd on the DOS screen.

Programs in a bat file are launched using the start command and specifying the name of the program to be launched.

The file can also contain the full path to the executable file.

Both of these entries work correctly for firefox. However, they are both correct only for applications registered in Windows. If you try to launch a portable program (for example, filezilla) without specifying the entire path to the file to be launched, it will not start.

Long names in bat files

Sometimes in bat there are programs that do not work with long names with spaces - usually these are some old programs for MS-DOS. In these cases, using short DOS names without spaces and quotes helps.

Rules for writing short DOS names (format 8.3): the initial six characters of the folder name are used, not including spaces, then its number is indicated in order through ~. For example: start C:Program FilesMozilla Firefoxfirefox.exe is converted to: start C:Progra~1Mozill~1firefox.exe.

It is possible that in one directory there are several folders with the same symbols in the name.

Their short names in this case should be numbered in accordance with the alphabetical order of the folders:

  • Mozill~1;
  • Mozill~2;
  • Mozill~3.

However, if Mozilla Firefox is removed from the computer, the entries following Mozill~1 will not work. Therefore, short DOS names are not the best solution to the problem of long names. Creation of names of this type on NTFS can also be disabled in the Windows registry.

To solve the problem of long names, the entry can also be enclosed in quotation marks. The quotation marks “”, located before the specified path to the file to be launched, are a required attribute that includes any header or only quotes.

However, in some cases quotes don't work at all. In this case, it is possible to use the Chdir (CD) command to change the current working directory. The start firefox.exe entry in this case takes on the following working form.

Reference. The CD command is perhaps the only universal solution to the issue of long names in bat files.

You can not only run programs in a bat file, but also install additional launch commands (keys) for them. For example, if you run a bat file with the entry: start /?, it will display on the DOS screen a list of keys used with this operator with the necessary explanations.

An example of the keys used, where: - minimize - a key for minimizing the program after it has been launched, - hide_splash - a key for minimizing the program to the tray.

Reference! Everything related to the .exe files that are launched is written with them in the bat file in a common line.

The folder creation command is executed in bat using the MKDIR (MD) operator. If you run the example bat file, it will create four subfolders on drive C.

The following example is how to open not one, but several directories at once on drive C.

The following example shows how to copy a folder from drive D: to drive E. The /s switch allows directories and subdirectories to be copied. The i/ option creates a new directory for the xcopy command to copy files into.

The base file remains both on drive D and is copied to a new location specified in the bat file.

Editing bat


Editing programs

For an ordinary user, the functionality of a simple Notepad may be enough to interact with bat files, but, for example, a system administrator needs a more powerful editor. You can work with bat in any text editor aimed at interacting with code, in particular, in Notepad++ or Notepad2.

Among the specialized software, we can note the Dr.Batcher utility, specially designed for creating bat, and including a visual editor, highlighted syntax, bookmarks, special commands and page numbering.

Video - How to create a bat file in Windows 10

Anyone can write bat files!

Command processor

Many operating systems, including those developed by Microsoft, include a command processor. This is the name of a program that initiates the execution of various actions in response to commands entered by the user from the keyboard. Basically, these actions consist of launching the necessary programs with certain parameters. But not only; We will see later that some commands are executed directly by the command processor. Basically, these are the commands that serve to control the context and sequence of command execution. However, we won't think too deeply about the nature of commands, at least not unless we have to. More importantly, any program that is technically possible to run from the command line is considered by the command processor as a command. It does not differentiate between the native commands that were originally built into the operating system and programs that were installed on top of it.

To start the command processor:

    Click on the button Start. The main menu will be displayed on the screen.

    Select Run from the main menu. A dialog box will appear on the screen Starting the program.

    In the Open field, enter the string cmd.

    Click on the button OK. A command processor window will appear on the screen.

Command line and commands

The command processor window in its original form looks gloomy, and working with it is not very convenient for most people. It's much easier to use Norton Commander-style file managers. They provide both tools for quickly navigating the file system and timing for entering commands.

To enter the command:

    Type the command text at the command line.

    Press the key Enter.

The command processor and operating system commands are described in the operating documentation for the latter. This documentation is partially contained within the operating system itself. To access it use the command help. This command displays a list of available commands. To get a description of a specific command, use the command as a parameter help her name should be indicated. The command line shown in the following listing displays a description of the command for.

If you tried to enter the command help, you probably noticed that the result of its work (the so-called output) does not fit on one screen. The same problem occurs with the command description text for. The good news is that output can be redirected to a file. The command line shown in the following listing generates the file commands.txt, containing a list of all MS-DOS commands.

help > commands.txt

In order to generate a file with a description of the command for, you need to give the following command (you can make the output file name anything).

help for > for.txt

In total, modern Microsoft operating systems contain slightly less than 80 commands, and it is impossible to describe them in one article. Here we can only mention a few commands useful for automating file processing and show how to use them. These commands will be used in further examples. You can always clarify the details by command help or in the directory.

copy- copying one or more files;

del- deleting one or more files;

move- moving one or more files or directories;

rename(abbreviated ren) - renaming one or more files or directories;

xcopy- copying the subdirectory tree;

mkdir(abbreviated md) - creating a directory;

rmdir(abbreviated rd) - deleting a directory.

One of the general rules of MS-DOS command syntax is that when specifying parameters, the source is specified first, and then the result. For example, if we want to move a file beer.txt from the catalog box to the catalog table, we must enter the command given in the following listing.

move box\beer.txt table

First what to move, then where to move.

If we want to rename the file lena.txt to file natasha.txt, then the command should be written as shown below.

ren lena.txt natasha.txt

First, what to rename, then what to rename.

Current directory. Absolute and relative paths

When working with file commands, the concept of the current directory becomes extremely important. The point is that when specifying a file as a command parameter, we always use one of two possible ways to point to them: either an absolute path or a relative path. In the full path we specify everything starting with the drive (or network name of the computer), for example d:\misha\box\beer.txt. Whatever directory is current when the command is entered, the full path will correspond to the same file. For a relative path, the current directory serves as the starting point. The simplest case of a relative path is a file name. In the context of command execution, it means a file with that name located in the current directory.

To write a relative path to the current directory, there is a conditional entry . (dot). To record the relative path to the directory that contains the current directory, there is a conditional notation .. (two dots). The command shown in the following listing copies all files from the current directory to the directory neighbor, located next to it.

copy *.* .\neighbor

Batch files

Until now, when giving examples, we assumed that we were entering commands manually every time. When processing a large number of files or systematically executing the same commands, this becomes cumbersome. Therefore, the command processor provides the ability to execute command files. A batch file is a text file in which commands (or at least one command) are typed. An example batch file is shown in the following listing. Try to guess what this batch file does.

help copy > copy.help

help move > move.help

move *.help msdos-help

If the purpose of this file remains a mystery to you, then try to actually create and execute it. It is customary to give command files the extension bat. This is how files of this type are recognized by the command processor. This file can be called, for example, make-help.bat.

To run the batch file:

    Enter his name as a command. After this, the batch file will be executed.

In a batch file, each command takes up one line. More precisely, there is a way to place one command on several consecutive lines; to do this, immediately before each line break you should put the “cap” symbol ^ . (Each cap must be the last character on its line; there must be no spaces or tabs after it.) An example of such a command is shown in the following listing.

if exist disser.txt ^

copy disser.txt ^

d:\science\papers\drafts\sources

But for the sake of simplicity, so as not to make reservations every time, we will assume that in a sense this is one long “logical” line.

When a batch file is executed, the command processor scans it from top to bottom from the first line to the last and executes the commands in the order in which it encounters them. It performs them in general as if we entered each of them manually. In general, because some commands behave slightly differently when entered manually and when executed from a batch file.

Looking ahead, let's say that, if necessary, the sequence of command execution can be changed using control commands (what may cause such a need is a separate question).

Do not confuse the current directory with the directory in which the batch file to be launched is located. Let's assume the current directory is work, it contains a directory tools, and the tools directory stores batch files. You launch one of them with the command tools\collect-images.bat. So, “from the point of view” of this command file, the current directory will still be work, but not tools.

Commenting the batch file and its output. echo and rem commands

A batch file is essentially a program written in the operating system's command processor language. The text of the program should be provided with comments so that, when you return to it some time later, you don’t have to painfully remember why this program is needed and how it works.

The MS-DOS command system provides a command for creating comments: rem. This is a fictitious command that does not involve performing any actions, but allows you to write arbitrary text on the line after your name. Moreover, the command processor does not perceive it as a syntax error. An example of formatting a command file with comments is shown in the following listing.

rem ************************************************* ****

rem Generating help files

help copy > copy.help

help move > move.help

move *.help msdos-help

Notice the empty lines that break up the batch file into “paragraphs.” This simple trick allows you to make a batch file more readable.

When executing the above batch file, all commands will be displayed on the screen as they are executed, which is not always convenient. Command issuance can be disabled using the command @echo off. Dog symbol in front of the command echo This means that this command itself must be executed in “silent” mode. We might as well not use the command line echo off, but place a “dog” in front of each command.

In many cases, you want a batch file to display certain messages on the screen (or in a file). In some cases, these may be error messages, in others, informational messages explaining to the user of the batch file what is happening at the moment, when we create some other useful file with the batch file. The same echo command is used to display messages. The text of the message to be displayed is passed to it as a parameter. The listing of the improved batch file is given below.

rem ************************************************* ****

rem Generating help files for the copy and move commands

rem ************************************************* ****

@echo Generating help files. One second...

rem Generating help files

help copy > copy.help

help move > move.help

rem Create a directory to store help files

rem Move the help files to the prepared directory

move *.help msdos-help

echo Done!

Passing parameters to a command file

Let's say we want to create a batch file that first generates help describing a user-specified command, and then loads it into Notepad for viewing. The trick is to somehow tell it the next time we run the batch file which command we are interested in this time.

To solve this problem, a parameter processing mechanism is provided. It works quite simply. If, when running a batch file, the user specified several parameters, then in the text of the batch file we denote the first of them with the entry %1 , second entry %2 , third entry %3 etc. We use these notations in the text of the command file in much the same way as we use pronouns in natural speech.

The text of the command file that solves the problem is shown in the following listing. Pay attention to the command help. The first parameter of the command file is passed to it as its parameter.

rem We create a file with a description of the command,

rem whose name is passed as a parameter

help %1 > help.tmp

rem Load the description file into the Notepad editor

notepad help.tmp

Let's assume we give this batch file the name show-help.bat. To load a command description into a notepad, for example, dir, we have to enter the command as follows.

show-help.bat dir

The following command file creates a directory with the name specified in the first parameter and writes into it a file containing the text describing the command specified in the second parameter.

rem Example of a command file with two parameters

rem Create a directory with the name specified by the first parameter

rem Create a file in it with a description of the command,

rem specified by the second parameter

help %2 > %1\%2.help

What happens if the user specifies four parameters rather than two when running this batch file? It's okay, they won't interfere with anything, they just won't be used. What happens if the user specifies only the first parameter? The second parameter will be empty. The effect will be this: the batch file will be executed, but as if in place of the recording %2 there is nothing. The help command will generate a list of all commands and place it in a file with an empty name and the extension .help. If the user runs this file without specifying any parameters, then when the command processor tries to execute the command md(remember, this is for creating a directory), we will get a syntax error because the md command must have a parameter.

Thus, using parameters creates great opportunities, but can significantly complicate things. In order for the batch file to always work correctly, it is necessary to check the correctness of the user's specified parameters and somehow respond to incomplete or incorrect input data. You can, of course, not do this, but an incorrectly working batch file can cause problems, especially if it involves deleting or overwriting data.

Variables. set command

A variable is a named value. In programming textbooks, a variable is usually compared to an envelope with a name written on it. You can put something inside the envelope, for example, a certain amount of money - this is its value. As with the envelope, the value of the variable can be changed.

To declare a variable and at the same time assign a value to it, use the command set. An example of this command is shown in the following listing.

To extract the value of a variable, its name is placed between two percent signs, as shown below.

rem Compiler of help files in CHM format

set help_compiler=c:\HTML Help Workshop\hcc.exe

rem Project help file for the "Warehouse" module

set store_hpj=help\sources\store\store.hpj

rem Project help file for the "Sales" module

set sales_hpj=help\sources\sales\sales.hpj

rem Compile help files

%help_compiler% %store_hpj%

%help_compiler% %sales_hpj%

The following listing shows why variables are useful.

Firstly, they allow you to use a short fragment synonymous with it inside a batch file instead of a long fragment (for example, the path to the help file compiler). At least it's convenient.

Secondly, they allow you to avoid repetition in the text of the command file of fragments that may change in the future. Imagine that we reinstalled Microsoft HTML Workshop to a different directory. If a variable is used in a batch file to record the path to it, then it will be enough to correct only one line in the batch file, namely, the one in which the value of the variable is assigned help_compiler. If we wrote the path to the compiler every time it needed to be called, then after changing the path we would have to correct each such line. In the given example there are two of them, but in a real project there could just as easily be five or fifteen of them, depending on the number of help files that we want to compile. The problem is not that manually correcting each line is difficult (after all, no one has canceled the “copy” and “paste” commands), but that this greatly increases the likelihood of an accidental error.

Batch file parameters are also variables, but they differ from ordinary variables in that their values ​​are set when the batch file is launched. In the future, when talking about variables, especially about working with their values, we will also mean command file parameters, at least in the absence of explicit reservations about this.

When writing batch files, the following technique is often used: several variable values ​​are indicated side by side (or interspersed with some symbols or lines), so as to obtain some new meaningful value. An example is shown in the following listing.

Checking conditions and selecting options. if and goto commands

The if command allows you to select groups of commands in a batch file that are executed or not executed depending on certain conditions. What is it for?

Condition checking is almost a necessary step when creating batch files that use parameters. Before starting work, the batch file generally needs to make sure that the correct set of parameters is passed to it. Otherwise, there is a high risk that it will be executed incorrectly or ineffectively, and the user will only be left wondering what the problem is. Moreover, if a batch file deletes, moves, or overwrites any data, it can even cause damage if the parameters are incorrect.

The following listing shows the help file compilation command file that you are already familiar with. A check for non-emptyness of the first parameter has been added to the beginning of the command file. Please note this syntax feature: the comparison operation uses a double equal sign. If the first parameter is non-empty, the goto command is executed, which “throws” the shell to the specified label. In this case, the name of this label is compile. Note that where a label appears, its name is preceded by a colon, but in the goto command it is not. If the first parameter is empty, the shell moves to the next line, which produces an error message. And then to the next one, which transfers it to the very end of the file to a label with the name finish.

if not "%1"=="" goto compile

rem If the parameter is empty, we display an error message

echo Help file project name not specified

rem and go to the end of the batch file

rem to finish mark

rem This is a label named compile

rem Below are the compilation commands

rem Path to the help file compiler

set help_compiler="c:\Program Files\HTML Help Workshop\hhc.exe"

rem Path to the directory where the help file projects are located

set project_path=e:\work\projects\help-projects

rem Call the compiler to process a specific project,

rem whose name is passed in the first parameter

%help_compiler% %project_path%\%1.hpj

rem This is a label named finish

Let's face it, the proposed method of checking a parameter is not the most successful.

First, if the user mistakenly specifies the name of a non-existent file as a parameter, the batch file will be satisfied with this and attempt to compile. A more correct way is to check whether such a file actually exists. For this purpose, the MS-DOS command language provides a special word exist. Therefore it would be better to write: if exist %1.hpj goto compile.

Secondly, active use of the command goto(the so-called unconditional jump) and labels greatly confuse the code. Technically, they are not bad, but debugging and maintaining a batch file written in this style is quite inconvenient. Therefore, programmers have long considered unconditional jumping an undesirable technique. Below is shown a more correct, from the point of view of programming style, structured version, which uses the construction if...else. It works like this: if the condition is true, the commands in parentheses after if, and if false, then in parentheses after else.

rem Check if the parameter is set

if not exist %1.hpj (

rem Path to the help file compiler

set help_compiler="c:\Program Files\HTML Help Workshop\hhc.exe"

rem Path to the directory where the help file projects are located

set project_path=e:\work\projects\help-projects

rem Call the compiler to process a specific project,

%help_compiler% %project_path%\%1.hpj

Let's give another example of working with checks. The following batch file creates a directory called help-files(suppose, to upload compiled help files into it). Moreover, if a directory with the same name already exists (and it probably contains old help files that you wouldn’t want to lose: what if the new ones turn out to be worse?), the batch file assigns the bak extension to it. But if the directory help-files.bak already existed, then the batch file deletes it (we will assume that one backup copy is enough for us).

if exist help-files.bak rd help-files.bak

if exist help-files ren help-files help-files.bak

Bulk file processing. for command

The for command allows you to organize the execution of repeated actions of the same type. You can use it to display the numbers one through ten, as shown in the following listing.

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

Variable i called a loop counter. Due to the unique syntax of the command for, the name of the loop counter must consist of one letter. Moreover, if we are writing a batch file, then we need to put a double percent sign in front of the name of the loop counter, but if we are just typing a command on the command line, then a single one.

The logic of this command is as follows. After the word in the range of change of the cycle counter is indicated. In this version of the command, this is a triple of numbers: the initial value of the counter, the counting step, the limit value of the counter. When executing a command, the shell will first assign the variable i meaning 1 , and then at each step of the loop it will increase it by 1 until it exceeds 10 . Obviously, there will be ten such steps. If we specified a number as the count step 2 , then the loop would be executed five times. At each step of the loop, the body of the loop written after the word is executed do. In the example above, this is the echo command, which displays the current value of the loop counter.

You can probably think of a situation where something like this is actually required, but usually the command for used to iterate and process files. It must be said that in fairly simple cases, bulk file processing is performed using wildcards. If we want to replace all files in the current directory with the extension .htm on .html, we enter the command ren *.htm *.html. But if the same thing needs to be done not in one directory, but in a directory tree, then you cannot do without the for command. The following batch file performs this operation for all htm files in the website subdirectory of the current directory. More precisely, in the entire directory tree that is inside website.

for /r website %%i in (*.htm) do ren %%i %%~ni.html

Key /r indicates the need to traverse the directory website and all its insides. If you do not specify it (but then you are not allowed to specify a directory), then only files in the current directory will be processed. The range of loop counter values ​​in this command variant is the set of all files with the extension .htm, located inside a directory (more precisely, a tree) website. A strange entry at first glance ~ni means that from the value of the variable i You only need to select the file name. The MS-DOS command language provides several such modifiers, for example, writing ~xi denotes the file extension. All modifiers are described in the command help for.

The body of a loop can consist of several commands enclosed in parentheses.

for /r website %%i in (*.htm) do (

rem Print the file name

rem Rename the file

ren %%i %%~ni.html

Transferring control to another batch file. call command

It is possible to call another batch file from one batch file. The command for this is call. Great, the variables set in the calling batch file are “visible” to the called one. And vice versa, after the called file finishes its work and returns control to the caller, the latter will “see” the variables left to it by the called “inheritance”. This allows the batch file developer to do something like this: If several command files must use the same values, for example, paths to some files, they can be placed in a separate command file, which will play the role of a configuration file. Each working command file will begin with a configuration call. The benefit is that when changing paths, you only have to make changes to one configuration file, and not to many workers.

"Configuration" batch file config.bat.

rem Path to the help file compiler

set help_compiler="c:\Program Files\HTML Help Workshop\hhc.exe"

rem Path to the directory where the help file projects are located

set project_path=e:\work\projects\help-projects

"Working" batch file.

rem Setting up variables

rem Check if the parameter is set

if not exist %1.hpj (

rem If the parameter is empty, we display an error message

echo This help file project does not exist.

rem Below are the compilation commands

rem Call the compiler to process a specific project,

rem whose name is passed in the first parameter

%help_compiler% %project_path%\%1.hpj


A bat file is a text file in Windows operating systems that contains a sequence of system commands for execution by the command interpreter “cmd.exe”. In general, it is a script file. After launching the bat file, the command interpreter reads its contents line by line and sequentially executes the received commands. Today we’ll look at how you can create a bat file, and also get acquainted with programs for creating and editing these files.

The purpose of bat files

Files with the bat extension are designed to automate many routine tasks in the Windows operating system. They will be very useful in cases where it is necessary to perform some operation or sequence of operations a large number of times in a row or periodically repeat a certain algorithm. First of all, this concerns working with the file system (creating a large number of directories, especially nested ones, mass renaming of files). , You can find out by clicking on the above link.

Creating a bat file

Any user can create a text command file - there is absolutely nothing complicated here. To do this, you only need a text editor (the functionality of a standard notepad will be quite sufficient).

First method

  1. Create a new text document in any directory.

To perform this action, call up the context menu of the directory space free of folders and files and select “Create”. In the drop-down list, click on the “Text file” item.

  1. Enter the name of the created document and click “Enter”.
  2. Open the created file by double clicking the mouse.

  1. Let's enter a few simple commands into it to check its functionality:

@ echo Hello, im bat!

@echo – command to display text on the screen;

Hello, i’m bat! - the text itself;

pause – wait for user actions before closing the window. After executing the “@echo” command, the command interpreter will not close automatically, allowing the user to get acquainted with the results of its execution (we will see the entered text on the screen).

  1. Call up the “File” item in the main notepad menu and click on “Save as...”.

  1. In the dialog that appears, select the file type “All files”.

  1. Next, we add the following text “.bat” to the name of our document, which will ultimately give “file.bat”.
  2. Click on the “Save” button.

As a result, a document called “file.bat” will appear in the Explorer window, to launch which you need to double-click on it with the left mouse button or select it and press “Enter”.

Editing a batch file is done by selecting the “Edit” command from its context menu.

Second method

The second method of creating bat files is almost similar to the first, but we will not ignore it.

  1. We launch Notepad using any known method.
  • Through the shortcut in the Start menu - go to “Start - All Programs - Accessories - Notepad” in Windows 7 or “Start - All Applications - Accessories - Windows - Notepad” in later editions of Windows.
  • In the search bar “Start” / “Windows”, enter notepad and launch the program by clicking on its shortcut in the list of results.
  • Call up the window for executing system commands using the key combination “Win ​​+ R”, enter “notepad” and click “OK”.
  1. Let's move on to point No. 4 of the previous method.

Editing bat files using Windows

  1. Right-click on the bat file, calling up its context menu.

  1. From the menu that appears, select “Edit” or “Edit”.
  2. The contents of the bat file will appear in the window that opens with a standard text editor, usually Notepad.
  3. We make the necessary adjustments and save the result.

Dr.Batcher – a program for creating bat files and editing them

Even though the use of bat files is not so popular among users today, it is still more effective to resort to their help to solve many problems on a computer. If a beginner who occasionally uses a command interpreter is satisfied with the functionality of Notepad, then for a system administrator and a Vareznik who creates builds of Windows or automatically installed software for it, a more advanced and convenient tool for working with documents in bat format is needed. It is the Dr.Batcher utility. The interface and functionality of the program is not much different from notepads such as Notepad++. The main menu contains buttons for frequently used commands. Dr.Batcher numbers pages, supports bookmarks, contains a list of system commands for bat files and highlights the syntax of entered commands.

Creating a bat file in Dr.Batcher

  1. Let's launch the application.
  2. Call the “File” item in its main menu and click “New”. The same is done by clicking on the blank sheet icon located under the “File” menu.
  3. In the dialog box, select “Empty Batch File”.

A program window will appear on the screen with all the functions necessary for working with bat files.

Editing bat files in Dr.Batcher

There are several ways to open a bat format document for editing in Dr.Batcher, which will be discussed further.

Editing via the context menu of a bat file

  1. Call the context menu of the bat format document.
  2. In the drop-down list, select “Edit with Dr.Batcher”.

Then a program window will open with the contents of our text batch file, where you can make adjustments to its contents.

Editing bat files using Dr.Batcher

  1. Launch the Batcher application.
  2. Call the “File” item in its main menu.
  3. Select “Open” from the drop-down menu.

The same thing is done by clicking on the folder icon located under the main menu.

  1. In the file opening dialog box, specify the path to the required bat format document and click “Open”.

Our bat file will open in the Dr.Batcher window and you can make adjustments to it.

If you have any questions about the topic "How to create a bat file? Programs for creating and editing bat files", you can ask them in the comments


if(function_exists("the_ratings")) ( the_ratings(); ) ?>