How to set up smartphones and PCs. Informational portal

All about bat files. Creating BAT files

People who are familiar with the term batch file know that BAT files can significantly simplify life and save time if you know how to write and use them correctly. In this article, I will talk about how to create BAT files and introduce you to common mistakes that usually occur when writing them.

Creating a BAT file is very simple. Just open Notepad and save a blank sheet with the .bat extension, selecting the Save as... option and writing in the File name field something ending in .bat, for example test.bat.
Specify the file type as in the screenshot below - All files. Save and receive a BAT file.

You can edit the BAT file in Notepad or any other text editor focused on working with code.

Now let's move directly to practical information. Many people on the Internet are looking for an answer to the question: How to deal with spaces in BAT files? . In paths to folders and executable files, the presence of a space causes an error. The most common answer is: Enclose the path in quotes. And this answer is not correct. True, some will foam at the mouth and claim that it works. So, two whys appeared - why it is not true and why some will be.

On Windows (as well as on UNIX), programs installed on the system are registered accordingly by the system. Therefore, some of the installed programs can be launched with one simple command from a BAT file or from the Run applet of the Start panel. One such program is Firefox:

start firefox

If after this command you write the path to the executable file, then the following happens: the Firefox browser starts and tries to process the request, that is, the file whose path is specified. That is, if you specify the following:

start firefox C:\Program Files\Mozilla Firefox\firefox.exe

The browser will open, no matter what it says after start firefox . That is why some comrades will assure that everything works great. However, if you take a portable program, the situation will be completely different. Let's take the Filezilla ftp client as an example. Since the system does not know about the program, the above line

start filezilla

won't work. To run a program unknown to the system, you need to specify the path to it:

start D:\FileZilla\FileZilla.exe

Long names in bat files

Now let's talk about paths and spaces. The first way to avoid this problem is to use a short name.

start C:\Program Files\Sound Club\scw.exe

In the example there are two names with spaces. Let's replace them with short ones. The rules for creating short names are as follows: the short name uses the first six characters of the name, excluding spaces, after the name the serial number of the folder is indicated using the symbol ~ . Since my Program Files and Sound Club folders are singular, it will look like this:

Program Files - Progra~1 Sound Club - SoundC~1 start C:\Progra~1 \SoundC~1 \scw.exe

If there are two folders nearby, for example Sound Club and Sound Clown, then following the rules, in the example above you will need to specify SoundC~2, since in this case Sound Club will be the second name (names are counted in alphabetical order).

But this method is inconvenient because you have to indicate serial numbers. The situation with Program files is more or less normal. Few people will find two similar folders on the system drive. But if you decide to install multiple Mozilla products on your computer. You will end up with several folders, for example:

Mozilla Firefox Mozilla Thunderbird Mozilla Sunbird

Short names for them will be

Mozill~1 Mozill~2 Mozill~3

Now imagine that you wrote a BAT file mentioning these programs. If you uninstall Firefox, the remaining entries will no longer work, and if you uninstall Thunderbird, the entry for Sunbird will no longer work. In short, the method with short names is not our way.

Spaces and quotes in bat files

Quotes actually work, but not in the ways that are usually advised. The following is usually advised:

start "C:\Program Files\Sound Club\scw.exe"

So the command will not work, because if you look at the help for it (start /? ), then in the help you will see the following:

START ["header"] [command/program] [parameters]

As you can see, the first parameter is the window title and it is in quotes. This parameter is optional, but it is still recommended to specify it () to avoid errors when executing the command. You don't have to write anything inside the quotes. It will turn out like this:

start "" "C:\Program Files\Sound Club\scw.exe"

The option of enclosing all names with spaces separately in quotes will also work:

start C:\"Program Files"\"Sound Club"\scw.exe

However, in some cases, none of the above works. In such cases, I can recommend using the cd command. Go to the system partition, then use cd to the Program Files folder and run the program (start):

%SystemDrive% cd \Program Files\Sound Club\ start scw.exe

I think this method will work everywhere. Now a couple more important points. Let's say you have created a batch file that launches three programs and you need to temporarily exclude the launch of one of the three. This can be done by deleting the line or commenting it out. The first method is vandal, and the second, see below.

start firefox start jetaudio rem start defraggler

In this case, the launch of the Defraggler.exe program installed on the system is disabled. Comment lines by specifying the rem command at the beginning of the line. All BAT files are executed in a console window. To make it disappear when the commands are completed, do not forget to write the exit command at the end.

start firefox start jetaudio rem start defragler exit

Launching applications from a bat file

In the first part of the article, I spoke in general terms about BAT files. Now it has become clear what it is and what it is eaten with. In the second part we will talk about more specific things. For example, how to use a BAT file to launch several applications with certain settings or install a program automatically so as not to waste time on answers like Do you agree to the terms of the license agreement? and don't press unnecessary buttons.

Several ways to launch applications using a BAT file were outlined above. The very first one is a short command to launch the program installed on the system.

start firefox

This doesn't always work. Therefore, this technique can be fully applied to a specific system, but it is not suitable as a universal solution. If your goal is to make the BAT file work everywhere and always, you need to use full paths:

start C:\"Program Files"\"Mozilla Firefox"\firefox.exe

I also noted that the BAT file must contain a command to complete:

start C:\"Program Files"\"Mozilla Firefox"\firefox.exe exit

Running programs in bat files with parameters (keys)

You can not only run the program, but also give it additional commands when starting it. For example, command to run minimized:

start /min D:\FileZilla\FileZilla.exe exit

To command in this case means to indicate the key. The key is indicated with a slash after the main command (command / key). The main command in this case is start . True, the min key only works in half the cases, because it relates specifically to the start command, and not to the programs that this command launches.

In general, there are a lot of keys and the sets of keys for different programs can vary significantly. There are, however, a few common ones. For example, the help key (/? or /help). To see how this key works, let's look at a practical example. Open the console (Click + R , enter cmd , then Enter ) and type the following in the console:

start /?

The console will display a list of valid keys with comments for the start command.

Pay attention to the /wait switch. In some cases, it is simply irreplaceable. For example, you decided to use a BAT file to unpack the archive with the program and run this very program. The batch file will contain two commands - for unpacking and for launching. Since the commands will be executed almost simultaneously when running the BAT file, the archive will not have time to unpack and there will be nothing to run. Therefore there will be an error. In this case, the key will come to the rescue /wait:

Thus, the system will first perform the first action, wait for it to complete, and only then proceed to the second. If you need to wait a specific period of time, it is easier to use a console utility. In the right place in the BAT file, write the following command (the number is the number of seconds):

start Sleep.exe 15

You can do a lot with keys. It is possible to install applications. To do this, several keys are used depending on the type of installer used to install the program on the computer:

/S /s /q /silent and a number of others

In some cases it can be very convenient. Avast antivirus has a silent installation option in the corporate version. The free (home) version supposedly does not have a silent installation. However, if you know how the InstallShield installer works, you will understand that this is a canard, since this installer itself supports the /S silent installation switch. This means that all products made on its basis do the same. And Avast is no exception. Just create a file with the contents in the folder with Avast's BAT

start avast.exe /S exit

you launch it and the program is installed on your computer with virtually no input from you. This way you can write a whole list of programs for silent installation and save time, for example, on reinstalling the system. In the article you can get more detailed information on the keys.

There are other options for managing programs using BAT files. You can start a program by telling it to open a file at startup. I use this method when developing websites. It’s very convenient when your entire toolkit opens the necessary documents and folders with the click of just one button:

rem connection to ftp server start /min D:\FileZilla\FileZilla.exe "ftp://login:password@server" rem opening index.php in Firefox start C:\"program files"\"mozilla firefox"\firefox.exe "http://localhost/site_folder/index.php" rem opening start.html in a text editor start /min C:\"Program Files"\text_editor.exe "E:\server\site_folder\index.html" rem opening the folder with site files start /min E:\server\site_folder rem console exit exit

I note that all the techniques described above can be used in various combinations and combinations.

start /min /wait program.exe /m /S start C:\Directory\program2.exe "C:\Files\file.odt" exit

But it is important to remember: everything related to the execution of the program launched in the batch file is written with it on the same line.

start C:\"program files"\"mozilla firefox"\firefox.exe "http://localhost/site_folder/index.php"

As an epilogue, I will offer for your review the converter of BAT files into applications in the .exe format - . A BAT file is not always aesthetically pleasing, but with the help of a converter you can pack a batch file into an exe file, decorating it with any icon of your choice.

I came across another BAT to EXE converter, you can consider it as an alternative to the previous program: Advanced Bat To Exe Converter

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 .\repository\

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 start executing 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 is a command that calls 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 contents of the shell that is 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 execution of the same actions.
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

Many technical writers have the need to automate file processing from time to time. Sometimes we are talking about one-time processing of a large number of files, sometimes we are talking about systematically performing the same actions, for example, when using DocBook or DITA technologies). Processing each file with a separate manual command not only takes time, but also leads to difficult-to-identify errors that arise due to the natural inattention of the operator.

In the MS-DOS operating system and in all operating systems of the Microsoft Windows family, the simplest means of automating the processing of files (and directories) are so-called batch files. Let’s say right away that batch files are not the only means of automating the user’s work, even among the built-in ones. In operating systems of the Microsoft Windows family, starting from version 98, there is also a Windows Script(ing) Host. In addition, no one forbids us to use some interpreted language for these purposes, say, Perl, Python or Ruby. However, the listed tools, although powerful, require programming skills, i.e. compose and, importantly, debug programs, at least at a good amateur level. Using batch files is accessible to anyone without special training; attentiveness and common sense are enough.

Important note. A complete reference book or even a well-written textbook on MS-DOS commands and the development of batch files would have to describe the numerous nuances associated with the use of various parameters, the peculiarities of the operation of batch files in different versions of Microsoft Windows, etc. and so on. This article does not claim to be complete, in particular:

  • we will not describe different ways to achieve the same result;
  • We will not describe all the possibilities and uses of the mentioned commands.

Now our task is to help those who are completely or almost unfamiliar with this tool begin to master batch files. You can then read about all the details in company documentation or reference books.

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:

  1. Click on the button Start. The main menu will be displayed on the screen.
  2. Select Run from the main menu. A dialog box will appear on the screen Starting the program.
  3. In the Open field, enter the string cmd.
  4. 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:

  1. Type the command text at the command line.
  2. 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.

Help 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, there are slightly less than 80 commands in modern Microsoft operating systems, 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) - rename 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 the result is specified first. 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 happens to be 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 md msdos-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:

  1. 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 run 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 dummy 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 using the copy and move commands rem ************************************ ***************** rem Create help files help copy > copy.help help move > move.help rem Create a directory for storing help files md msdos-help rem Move help files to the prepared one directory move *.help msdos-help

Notice the empty lines that break up the batch file into “paragraphs.” This simple trick allows you to make your 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. The "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.

@echo off rem ****************************************************** ******* rem Generating help files using the copy and move commands rem ********************************* ******************** @echo Generating help files. Just a second... rem Create the help files help copy > copy.help help move > move.help rem Create a directory to store the help files md msdos-help 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.

@echo off rem We create a file with a description of the command, rem whose name is passed by the parameter help %1 > help.tmp rem We 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 An example of a command file with two parameters rem Create a directory with the name specified by the first parameter md %1 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 matters. 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.

Rem Compiler of help files in CHM format set help_compiler=c:\HTML Help Workshop\hcc.exe

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 of the "Warehouse" module set store_hpj=help\sources\store\store.hpj rem Project help file of 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 above 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.

Rem Path to the help file compiler set help_compiler="c:\Program Files\HTML Help Workshop\hhc.exe" rem Path to the directory in which the help file projects are located set project_path=e:\work\projects\help-projects rem We call the compiler to process a specific project, rem whose name is passed in the first parameter %help_compiler% %project_path%\%1.hpj

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.

@echo off rem We check whether the parameter is specified if not "%1"=="" goto compile rem If the parameter is empty, we issue an error message echo The project name of the rem help file is not specified and go to the end of the rem command file to the finish goto label finish rem This is a label named compile: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 projects are located files 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: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 better 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.

@echo off 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.) else (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 in which 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)

Pay attention to the indentation from the left edge. They are optional, but make the text of the batch file more readable.

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 md help-files

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.

@echo off for /r website %%i in (*.htm) do (rem Print the file name echo %%i 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 specified 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 in which the help file projects are located set project_path=e:\work\projects\help-projects

"Working" batch file.

@echo off rem Set up variables call config.bat 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.) else (rem Below are the compilation commands rem We 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 mutually 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.

Today we will learn about what it is bat file and at the same time we will create one of them.

I think that many, one way or another, periodically create (so-called backups) certain files and folders.

Everything seems to be familiar and you don’t need to do anything particularly complicated: insert a flash drive, open “My Computer”, find what you need to copy, select, click with the mouse, select “copy”, move to the desired directory, click “paste”, etc.

But often all these clicks and unnecessary movements are somewhat tiring and take up valuable time, especially when frequently copying the same data. In this article I will tell you how, or rather, how to write such a thing as a bat file.

Go.

Bat file - what's what, introductory

First, a little about what a bat file is, why it is needed and what it (or them) is used with. In order not to reinvent the wheel, I will use an excerpt from Wikipedia:

A batch file (i.e. bat file, from the English batch file) is a text file in MS-DOS, OS/2 or Windows containing a sequence of commands intended for execution by the command interpreter.

After running a batch file, an interpreter program (usually COMMAND.COM or CMD.EXE) reads it line by line and executes the commands sequentially.

A batch file is analogous to a shell script in Unix-like operating systems.

Batch files are useful for launching applications automatically. The main area of ​​application is the automation of the most routine operations that a computer user regularly has to perform.

Examples of such operations include: processing text files; copying, moving, renaming, deleting files; working with folders; archiving; creating database backups, etc.

Batch files support the if and goto statements (and in Windows NT family systems, the extended for statement), which allows you to process the results of executing previous commands or applications and, depending on this, further execute this or that block of commands (usually, if the application completes successfully returns 0 in the errorlevel variable; if unsuccessful, 1 or greater).

Batch files in DOS have the extension .bat; for other operating systems they may have different extensions - for example, .CMD in Windows NT and OS/2, or .BTM in 4DOS or similar shells.

Now that we've sorted out the theory, let's get down to the actual practice, namely creating a bat nickname.

How to create a bat file and use it

Let's prepare a small test field so that we have something to experiment with. Open my computer and create a test folder on the C:\ drive. Go into it and create a folder in it.

Throw files there (5-10 pieces) - photos, documents, etc., etc. (anything shorter). The field for experimentation is ready. Next, we need to create, in fact, the bat file itself, by clicking on which we will copy the C:\test\testcopy folder to, say, the C:\test\backup folder. There is no need to create a second folder (which is backup) - it will appear automatically.

Creating a bat is very simple. Right-click where we want to create it (the location is not important - you can directly on the desktop) and select "Create" - " Text Document".

Give the created file a name and open it with notepad or any other text editor. Those. At the moment we have an open text file, which is called, say, copying.txt.

Add a command to the file, for example, to copy

Next, in fact, we need to enter a command into this file that will be played using the console (cmd) when this file is launched. In this case, we will use the xcopy command because it allows you to copy files, directories and subdirectories. Considering all the paths, we get the following command:

xcopy C:\test\testcopy C:\test\backup /f /i /y /s

Let me explain what's what:

  • xcopy is the command itself;
  • C:\test\testcopy is the source, i.e. the folder from which files and directories are copied;
  • C:\test\backup is the result, i.e. the location where files and directories will be copied;
  • /f /i /y /s - additional syntax parameters for the xcopy command (see syntax below).

The number of lines can be any, i.e. if you need to copy 100 folders, you write 100 lines in one file and change only the paths in them.

What are there (i.e. those that I indicated in this example):

  • /f - displays the names of the source files and the result files during the copying process
  • /i - creates a new directory if it is not in the final path
  • /y - overwrites the file if it already exists
  • /s - copies directories and subdirectories if they are not empty. If the /s option is not specified, the xcopy command will only work on one directory.

As for me, this is the main list of parameters necessary for “silent” copying, i.e. without unnecessary questions about rewriting, creating directories and other riffraff. Regarding the rest of the syntax, you can read, for example, .

Change the file format and try to run it

First, open "My Computer", go to "Tools" - "Folder Options" - "View" and uncheck " Hide extension for registered file types".

Click "Apply" and "Ok". Now we can change the extension of files known to the system, and therefore we go to our file, right-click, select “Rename” and by typing on the keyboard change the extension from txt to bat (we answer the system’s question whether this is worth doing in the affirmative).

As a result, we have the following picture (in your case the file is called differently, but has the same format):

Actually, all that remains for us is to launch this file by simply clicking on it with the mouse.

If you did everything correctly, then the console will flash in front of you and a new folder will appear along a known path with a predetermined name and files inside copied from a folder known to you, i.e. the picture will be something like this:

Well, or slightly different, depending on what paths and folder names you specified in the command.
You can edit the file by changing its extension back to .txt and opening it with any text editor.

Afterword

As I already said and you yourself probably realized, using a bat file like this often saves a lot of time, i.e. you write it once and periodically launch it with one click, and instead of many minutes of clicking with the mouse and crawling through all the folders, you get an automated copying process.

If you wish, you can set this bat nickname to run on certain days through the Windows scheduler (or other programs that allow you to do this) and generally forget about the problem of long manual backups.

If you have any questions or problems, ask. As always, I will help in any way I can;)

PS: If my memory serves me right, then this is a piece of a topic from smart admin books, namely from the section " Administration automation".. so you can be proud of yourself :)

Best articles on the topic