Как закомментировать строку в bat файле
Перейти к содержимому

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

  • автор:

REM – создание комментариев в командных файлах Windows.

Команда REM является встроенной командой интерпретатора команд cmd.exe и применяется для создания комментариев в командных файлах. Строка, начинающаяся с REM , не обрабатывается командным интерпретатором и может использоваться для пояснений, заметок и т.п., что бывает очень не лишним в сложных bat-файлах. Иногда, в качестве альтернативы команде REM используются приемы, основанные на особенностях реализации командного процессора cmd.exe , как, например, двойное двоеточие:

@ECHO OFF
::
:: Начало работы
REM
REM Продолжение работы
Echo Hello REM Этот текст будет полностью отображен командой ECHO
Echo Hello & REM Отобразить «Hello» командой echo
Copy 1.bat 2.bat & :: Копирование файла 1.bat в 2.bat
pause

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

сopy 1.bat 2.bat & rem Копирование файла 1.bat в 2.bat
Или
сopy 1.bat 2.bat & :: Копирование файла 1.bat в 2.bat

Такая конструкция позволяет поместить комментарий к отдельной команде bat-файла.

В качестве аналога пустой команды REM может использоваться пустая строка, которая так же игнорируется командным процессором CMD.

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

Иногда для создания комментариев используется прием, основанный на применении команды безусловного перехода GOTO, размещенной в самом начале командного файла на метку, соответствующую первой строке исполняемых команд. Поскольку интерпретатор команд CMD обрабатывает команды командного файла последовательно, любой текст между командой GOTO и меткой будет им проигнорирован. Соответственно, в этом месте можно, например, поместить поясняющий текст либо любой иной комментарий:

REM Это большой командный файл
Goto :Label1
Здесь можно разместить любой текст, который может быть подробным описанием командного файла.
:label1
Rem начало исполняемой части командного файла
@echo off
. . .

Как добавить комментарии в bat-файл

Как добавить комментарии в bat-файл

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

Примеры

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

Такое написание комментария при запуске пакетного файла передаст управление сразу к команде, следующей за меткой start. За это отвечает оператор перехода goto.
Более простые комментарии (из одной или нескольких строк) можно добавить, начиная строки с команды rem или с двух двоеточий, идущих друг за другом.

Комментирование больших пакетных файлов (как, в принципе, и любого кода) — хороший тон, который значительно облегчает процесс разбора этих файлов другими людьми или самим автором по прошествии значительного времени с момента написания.

Batch Script — Comments

It’s always a good practice to add comments or documentation for the scripts which are created. This is required for maintenance of the scripts to understand what the script actually does.

For example, consider the following piece of code which has no form of comments. If any average person who has not developed the following script tries to understand the script, it would take a lot of time for that person to understand what the script actually does.

Comments Using the Rem Statement

There are two ways to create comments in Batch Script; one is via the Rem command. Any text which follows the Rem statement will be treated as comments and will not be executed. Following is the general syntax of this statement.

Syntax

where ‘Remarks’ is the comments which needs to be added.

The following example shows a simple way the Rem command can be used.

Example

Output

The above command produces the following output. You will notice that the line with the Rem statement will not be executed.

Comments Using the :: Statement

The other way to create comments in Batch Script is via the :: command. Any text which follows the :: statement will be treated as comments and will not be executed. Following is the general syntax of this statement.

Syntax

where ‘Remarks’ is the comment which needs to be added.

The following example shows the usage of the «::» command.

Example

Output

The above command produces the following output. You will notice that the line with the :: statement will not be executed.

Note − If you have too many lines of Rem, it could slow down the code, because in the end each line of code in the batch file still needs to be executed.

Let’s look at the example of the large script we saw at the beginning of this topic and see how it looks when documentation is added to it.

You can now see that the code has become more understandable to users who have not developed the code and hence is more maintainable.

Comments

Regardless of the programming or scripting language used, it is always a good idea to insert comments in scripts, explaining what the next lines or block of code is trying to accomplish, how and/or why.

Comments in batch files are usually placed in lines starting with REM (REMarks).

If you have many lines REM ed out, this may slow down COMMAND.COM’s processing of the batch file.

As you probably know, COMMAND.COM reads a batch file, executes one command line, reads the batch file again, executes the next command line, etcetera.
This means each comment line causes one extra reread of the batch file; no problem when read from harddisk, but it may slow down batch file execution from slow floppy or network drives.

A workaround I have seen many times (back in the old days, when I was young, and dinosaurs roamed the Earth and harddisks were 20MB) is to convert the comment line to a label by starting the line with a colon ( : ).
COMMAND.COM skips labels it doesn’t have to jump to.

This method has the disadvantage that your batch file may «accidently» really use the label to jump to.

As Marc Stern points out in one of his MS-DOS batch files Tips & Tricks, this can be solved by using a double colon ( :: ) as the first characters of the comment line.
That way, the label is invalid but still treated as a label, and skipped (i.e. the next line is read immediately by COMMAND.COM, without the need to reopen the batch file). This may speed up reading large blocks of comment lines from slow (floppy) drives.

This same trick works in CMD.EXE (the command processor in Windows NT 4 and later) as well (not sure about OS/2 though).

. but with some restrictions!

REM is a true command that may be used anywhere within a command line.
Though I doubt there is much use for a command like:

it is valid and won’t generate an error message in any DOS or Windows version.

Labels, on the other hand, whether valid or not, should always start at the first non-whitespace character in a command line.

are all allowed.
However,

will result in a Syntax error message.

A true pitfall are code blocks, several commands grouped between parentheses and interpreted as a single command line by CMD.EXE!

will result in an error message stating:

) was unexpected at this time.

will result in another error message:

Do something
The system cannot find the drive specified.

The same is true for FOR loops.
Try and see for yourself:

will also result in error messages.

The errors are caused by labels being used within code blocks.

What may come as a surprise is that the following code does work flawlessly:

It turns out that a single :: comment line, immediately followed by a non-blank command line, will work even inside code blocks!

Replace the double colons by REM statements and these samples will all run without a glitch.
Better still, don’t use comments within code blocks at all, but place them just before the code blocks instead:

A Mystery:

The code above use 3 code blocks, each with a REM command followed by an ECHO command.
The 3 code blocks are followed by a fourth «stand-alone» ECHO command.
The 3 code blocks are supposed to behave more or less identically, at least in older versions like Windows NT 4 and 2000.

Well, in Windows 7 they don’t!

comment1 is the only comment ECHO ed.
The code block for comment2 only displays an empty line.
The code block for comment3 is never reached.

It would seem the code block for comment2 aborts the batch file without warning.
Remove that code block, and the rest will be executed as expected.

So, can you explain this behaviour.

The answer can be found at the end of this page.

More information on the subject:

  • Michael Klement’s summary of a discussion on comment styles on StackOverflow.com
    You will find even more comment styles here (like %= inline comments =% ), each with its own list of pros and cons

(Thanks for Lee Wilbur and Michael Klement)

A possible pitfall, pointed out by Joost Kop, is a REM to comment out a line that uses redirection, as in:

In CMD.EXE (Windows NT 4 and later) the line is completely ignored (as was probably intended), but COMMAND.COM (MS-DOS, Windows 9x) interprets this line as «redirect the output of REM to logfile.log», thus emptying the file logfile.log or creating a 0 bytes file logfile.log.

Note: I would like to mention one situation where I always prefer REM over double colons: batch files for silent installations.
Why?
I always leave out the @ECHO OFF since silent installations will usually run in the background.
When testing, however, I will run the batch files interactively, and then the REM ed comments will be displayed (remember, no @ECHO OFF ) because they are commands, not labels.

Summarizing:

  • REM is the standards-compliant, documented statement to insert comments in batch files
  • double colons are a non-documented and non-compliant way to insert comments; there is no guarantee they will still work in future Windows versions
  • in theory, using double colons may speed up execution of batch files when run from a slow disk drive (e.g. floppy disk), but I doubt the difference can be detected on modern computers
  • for large blocks of comment, a GOTO command just before the comments, jumping to a label just after the comments, is a safer and more standards-compliant way to speed up batch execution from slow drives
  • since double colons are actually labels, they should be placed at the start of a command line; though leading whitespace is allowed, nothing else is
  • using double colons inside code blocks violates the previous «rule» and will usually result in errors (except some special cases)
  • try to avoid comments inside code blocks, or use REM if you have to (but be aware of pitfalls if you do use REM )
  • with COMMAND.COM be careful when using either REM or double colons to temporarily «disable» a command line, especially when it contains piping, redirection or variables
  • despite all, there is nothing wrong with using double colons for comments as long as you understand the limitations
  • test, test, test and test your batch files, including comment lines, on all Windows versions they will be used for

Pipe REM to block Standard Input

A really useful trick is to use REM combined with piping, as in:

The CHOICE command in itself would time out after 5 seconds (/T), except if someone presses a key not specified by /C, in which case the count down would be aborted.
By using REM and piping its (always empty) standard output to CHOICE’s standard input, this standard input will not receive keypresses from the console (keyboard) anymore. So pressing a button neither speeds up CHOICE nor stops it.
(I borrowed this technique from «Outsider», one of the alt.msdos.batch newsgroup’s «regulars», and added the /C parameter to make it language independent)

TYPE NUL | CHOICE /C:AB /T:A,5 > NUL

Comment blocks

Several languages allow complete code blocks to be commented out by using /* and */ «tags».
Rexx, for example, will treat the whole text marked red as comment:

The batch language doesn’t have comment blocks, though there are ways to accomplish the effect:

Or, if the comment block appears at the end of the batch file:

Leo Gutierrez Ramirez came up with an even shorter way to accomplish a comment block at the end of a batch file:

Note: This trick does have one major disadvantage: the use of parentheses in the comment block is not allowed.

Mystery Solved

Recently, Vasco Rato showed me the solution to the mysteriously disappearing code.

If you read Leo Gutierrez Ramirez’ trick of the missing closing parenthesis, you’ll see that that is exactly what happens.
The following line of code:

is equivalent to

since everything following the REM statement, including the closing parenthesis, is comment, i.e. not interpreted!

Since there were no other parentheses in the «mystery code block» after this comment, everything from the opening parenthesis before the REM statement up to the end of the code is then a «Leo Gutierrez Ramirez style» comment block.

REM – создание комментариев в командных файлах Windows.

Команда REM является встроенной командой интерпретатора команд cmd.exe и применяется для создания комментариев в командных файлах. Строка, начинающаяся с REM , не обрабатывается командным интерпретатором и может использоваться для пояснений, заметок и т.п., что бывает очень не лишним в сложных bat-файлах. Иногда, в качестве альтернативы команде REM используются приемы, основанные на особенностях реализации командного процессора cmd.exe , как, например, двойное двоеточие:

@ECHO OFF
::
:: Начало работы
REM
REM Продолжение работы
Echo Hello REM Этот текст будет полностью отображен командой ECHO
Echo Hello & REM Отобразить «Hello» командой echo
Copy 1.bat 2.bat & :: Копирование файла 1.bat в 2.bat
pause

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

сopy 1.bat 2.bat & rem Копирование файла 1.bat в 2.bat
Или
сopy 1.bat 2.bat & :: Копирование файла 1.bat в 2.bat

Такая конструкция позволяет поместить комментарий к отдельной команде bat-файла.

В качестве аналога пустой команды REM может использоваться пустая строка, которая так же игнорируется командным процессором CMD.

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

Иногда для создания комментариев используется прием, основанный на применении команды безусловного перехода GOTO, размещенной в самом начале командного файла на метку, соответствующую первой строке исполняемых команд. Поскольку интерпретатор команд CMD обрабатывает команды командного файла последовательно, любой текст между командой GOTO и меткой будет им проигнорирован. Соответственно, в этом месте можно, например, поместить поясняющий текст либо любой иной комментарий:

REM Это большой командный файл
Goto :Label1
Здесь можно разместить любой текст, который может быть подробным описанием командного файла.
:label1
Rem начало исполняемой части командного файла
@echo off
. . .

How to "comment-out" (add comment) in a batch/cmd?

I have a batch file that runs several python scripts that do table modifications.

I want to have users comment out the 1-2 python scripts that they don’t want to run, rather than removing them from the batch file (so the next user knows these scripts exist as options!)

I also want to add comments to bring to their attention specifically the variables they need to update in the Batch file before they run it. I see that I can use REM . But it looks like that’s more for updating the user with progress after they’ve run it.

Is there a syntax for more appropriately adding a comment?

T.Todua's user avatar

12 Answers 12

Use :: or REM

BUT (as people noted):

  • if they are not in the beginning of line, then add & character:
    your commands here & :: commenttttttttttt
  • Inside nested parts ( IF/ELSE , FOR loops, etc. ) :: should be followed with normal line, otherwise it gives error (use REM there).
  • :: may also fail within setlocal ENABLEDELAYEDEXPANSION

T.Todua's user avatar

The rem command is indeed for comments. It doesn’t inherently update anyone after running the script. Some script authors might use it that way instead of echo , though, because by default the batch interpreter will print out each command before it’s processed. Since rem commands don’t do anything, it’s safe to print them without side effects. To avoid printing a command, prefix it with @ , or, to apply that setting throughout the program, run @echo off . (It’s echo off to avoid printing further commands; the @ is to avoid printing that command prior to the echo setting taking effect.)

So, in your batch file, you might use this:

No, plain old batch files use REM as a comment. ECHO is the command that prints something on the screen.

To «comment out» sections of the file you could use GOTO . An example of all these commands/techniques:

What can I say? batch files are a relic of times long gone, they’re clunky and ugly.

EDIT: modified the example a bit to have it contain the elements you are apparently looking for.

The :: instead of REM was preferably used in the days that computers weren’t very fast. REM’ed line are read and then ingnored. ::’ed line are ignored all the way. This could speed up your code in «the old days». Further more after a REM you need a space, after :: you don’t.

And as said in the first comment: you can add info to any line you feel the need to

As for the skipping of parts. Putting REM in front of every line can be rather time consuming. As mentioned using GOTO to skip parts is an easy way to skip large pieces of code. Be sure to set a :LABEL at the point you want the code to continue.

Multi line comments

If there are large number of lines you want to comment out then it will be better if you can make multi line comments rather than commenting out every line.

The batch language doesn’t have comment blocks, though there are ways to accomplish the effect.

You can use GOTO Label and :Label for making block comments.

Or, If the comment block appears at the end of the batch file, you can write EXIT at end of code and then any number of comments for your understanding.

Somnath Muluk's user avatar

Putting comments on the same line with commands: use & :: comment

Explanation:

& separates two commands, so in this case color C is the first command and :: set red font color is the second one.

Important:

This statement with comment looks intuitively correct:

but it is not a valid use of the comment. It works only because goto ignores all arguments past the first one. The proof is easy, this goto will not fail either:

But similar attempt

fails executing the command due to 4 arguments unknown to the color command: :: , grey , on , blue .

It will only work as:

So the ampersand is inevitable.

miroxlav's user avatar

You can comment something out using :: or REM :

To do it on the same line as a command, you must add an ampersand:

  • Using :: in nested logic ( IF-ELSE , FOR loops, etc. ) will cause an error. In those cases, use REM instead.

Pikamander2's user avatar

Commenting a line

For commenting line use REM or :: though :: might fail inside brackets

within delayed expansion lines starting with !<delimiter> will be ignored so this can be used for comments:

Comment at the end of line

For comments at the end of line you can again use rem and :: combined with & :

Commenting at the end of file

As noting will be parsed after the exit command you can use it to put comments at the end of the file:

Inline comments

Expansion of not existing variables is replaced with nothing ,and as setting a variable with = rather hard you can use this for inline comments:

Multiline comments

For multiline comments GOTO (for outside brackets) and REM with conditional execution (for inside brackets) can be used. More details here:

And the same technique beautified with macros:

npocmaka's user avatar

dp* =% didn't work. Combining both it finally worked: rem %= echo

dp*= % as a variable. The lonely

as a command and then it is commented with REM. Though a good way to avoid the REM %

I prefer to use:

  • REM for comments
  • &REM for inline comments

Jorge Cribb's user avatar

You can add comments to the end of a batch file with this syntax:

Just make sure you never use a closing parentheses.

Wasif's user avatar

This is an old topic and I’d like to add my understanding here to expand the knowledge of this interesting topic.

The key difference between REM and :: is:

REM is a command itself, while :: is NOT.

We can treat :: as a token that as soon as CMD parser encounters the first non-blank space in a line is this :: token, it will just skip the whole line and read next line. That’s why REM should be followed by at least a blank space to be able to function as a comment for the line, while :: does not need any blank space behind it.

That REM is a command itself can be best understood from the following FOR syntax

The basic FOR syntax is as follows

here <Command> can be any valid command So we can write the following valid command line as rem is a command

Как закомментировать строку в cmd

Как добавить комментарии в bat-файл

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

Примеры

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

Такое написание комментария при запуске пакетного файла передаст управление сразу к команде, следующей за меткой start. За это отвечает оператор перехода goto.
Более простые комментарии (из одной или нескольких строк) можно добавить, начиная строки с команды rem или с двух двоеточий, идущих друг за другом.

Комментирование больших пакетных файлов (как, в принципе, и любого кода) — хороший тон, который значительно облегчает процесс разбора этих файлов другими людьми или самим автором по прошествии значительного времени с момента написания.

How do I comment on the Windows command line?

In Bash, # is used to comment the following. How do I make a comment on the Windows command line?

Peter Mortensen's user avatar

Tim's user avatar

8 Answers 8

The command you’re looking for is rem , short for "remark".

There is also a shorthand version :: that some people use, and this sort of looks like # if you squint a bit and look at it sideways. I originally preferred that variant since I’m a bash -aholic and I’m still trying to forget the painful days of BASIC ��

Unfortunately, there are situations where :: stuffs up the command line processor (such as within complex if or for statements) so I generally use rem nowadays. In any case, it’s a hack, suborning the label infrastructure to make it look like a comment when it really isn’t. For example, try replacing rem with :: in the following example and see how it works out:

You should also keep in mind that rem is a command, so you can’t just bang it at the end of a line like the # in bash . It has to go where a command would go. For example, the first line below outputs all hello rem a comment but the second outputs the single word hello :

The second is two separate commands separated by & , and with no spaces before the & because echo will output those as well. That’s not necessarily important for screen output but, if you’re redirecting to a file, it may:

Batch File Comment (Remark) – Windows

A batch file (batch script) in Windows is a text file that typically has a .bat extension and includes one or more command prompt commands.

It is a good practice to comment a source code in a batch file by leaving the remarks that explain functionality of some lines or blocks of code.

Also any line or a block of code in a batch file can be disabled by turning it into a comment (comment out) and enabled back (uncomment).

This note shows how to comment batch files in Windows.

Cool Tip: Get the return code from the last command or application! Read more →

Batch File Comment

A batch file can be commented using either two colons :: or a REM command.

The main difference is that the lines commented out using the REM command will be displayed during execution of the batch file (can be avoided by setting @echo off ) while the lines commented out using :: , won’t be printed.

Create a comment (remark) or comment a line of code in a batch file:

A block of code (multiple lines) in a batch file can be commented out using GOTO :

Cool Tip: How to respond “Yes” or “No” to prompts in Windows PowerShell & CMD automatically! Read more →

How do I do comments at a Windows command prompt?

What’s the equivalent of # for Windows cmd console sessions, to create a comment?

The operating system is Windows XP.

That Brazilian Guy's user avatar

5 Answers 5

REM is the standard way:

You could also use the double-colon convention commonly seen in batch files:

A single colon followed by a string is a label, but a double colon and anything after it are silently ignored. One could argue that this form is more legible than the REM command.

Note that both of these methods only work at the beginning of a line. If you want to append a comment to a command, you can use them with the command concatenation character ( & ), like this:

How do I do comments at a Windows command prompt?

What’s the equivalent of # for Windows cmd console sessions, to create a comment?

The operating system is Windows XP.

That Brazilian Guy's user avatar

5 Answers 5

REM is the standard way:

You could also use the double-colon convention commonly seen in batch files:

A single colon followed by a string is a label, but a double colon and anything after it are silently ignored. One could argue that this form is more legible than the REM command.

Note that both of these methods only work at the beginning of a line. If you want to append a comment to a command, you can use them with the command concatenation character ( & ), like this:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *