Комментарий в командной строке windows


Windows

  • 25.01.2020
  • 60 604
  • 7
  • 185
  • 185
  • 0

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

  • Содержание статьи
    • Описание
    • Примеры
    • Комментарии к статье ( 7 шт )
    • Добавить комментарий

Описание

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

Примеры

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

goto start
--------------------------------------
Этот пакетный файл предназначен
для автоматизации рутинных операций,
выполняемых ночью для синхронизации
содержимого корпоративного ftp-сервера
с ftp-серверами филиалов
--------------------------------------
Пакетный файл написан 01/01/2004
Последнее исправление внесено 10/02/2004
--------------------------------------
И т.д.
:start

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

rem Этот блок устанавливает соединение с удаленным сервером
rem А это вторая строка с комментарием
:: Этот блок проверяет дату изменения файлов
:: А это вторая строка с комментарием

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

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:

if 1==1 (
    rem comment line 1
    echo 1 equals 1
    rem comment line 2
)

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:

echo hello rem a comment.
echo hello& rem a comment.

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:

echo hello >file          - includes the space.
echo hello>file           - no space.

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

asked Dec 12, 2009 at 7:47

Andrew Grimm's user avatar

Andrew GrimmAndrew Grimm

2,7206 gold badges30 silver badges37 bronze badges

3

REM is the standard way:

REM this is a comment

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

:: another comment

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:

dir & REM a comment
dir &:: another one

answered Dec 12, 2009 at 8:51

efotinis's user avatar

7

You prefix your comment with the word REM.

REM This is a comment.

But if you want your comment printed back to you, you should echo it:

echo This is a comment you'll see.

answered Dec 12, 2009 at 7:50

Bernhard Hofmann's user avatar

1

The REM command only remarks (i.e. Say something as a comment) the line from being executed. However, if @echo off is not in the batch file that line will still echo to the screen.

To prevent these lines from being shown you can do one of three things.

  1. Add @echo off to the batch file:
    If you want to hide all commands as well as the REM lines add @echo off as the first line in the batch file.
  2. Change the REM to @REM:
    If you want to have the commands shown when the batch file is run, but still want to hide the REM lines type @REM instead of REM.
  3. Use ::(i.e. invalid lable) instead of REM:
    Finally, using the :: as the remark command instead of REM also prevents the echo of the remarked line.

source

Community's user avatar

answered Mar 24, 2016 at 12:54

Premraj's user avatar

PremrajPremraj

2,1562 gold badges18 silver badges25 bronze badges

I believe the answer provided by bernhard is incorrect.

At least through win 7,

rem comment

in a batch file will print in the output. To suppress printing, use

@ rem comment

or

@rem comment

The same goes for other commands, which by default are echoed to the console.

answered Nov 22, 2014 at 21:41

pbpb's user avatar

pbpbpbpb

795 bronze badges

3

Everything started after exit (with a parentheses) is regarded as comment:

REM CODE
exit /b 0

(Hi
I am a comment
I am also the same

answered Sep 17, 2020 at 6:19

Wasif's user avatar

WasifWasif

8,0642 gold badges19 silver badges32 bronze badges

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

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 →

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:

:: This is a comment that won't be printed
- or -
REM This is a comment that will be printed

Inline comment:

ECHO "Hello" & :: This command prints 'Hello'
- or -
ECHO "Hello" REM This command prints 'Hello'

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

GOTO comment
...skip this...
:comment

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

Was it useful? Share this post with the world!

Rem (abbreviation of remark) is a command (internal) found inside the Windows Command Processor Command Prompt, that allows for inclusion of comments inside batch programs. Comments are supported by most Programming languages usually via special syntax that is associated to them. Ex. Python using pound sign/hashtag ( # ) to denote a inline comment. Rem command is for inline comments, therefore the comment would only be valid till the end of the current line (or first occurrence of CRLF) Though multiline comments can be created using multiple Rem command on separate lines. In this article we will take a look at the Rem command, and would get to know about various uses for it. 

Description of the Command :

Records comments (remarks) in a batch file or CONFIG.SYS.

REM [comment] 

*The above output can be obtained by executing rem /? command in the commandline

Using the Command : Comments are generally used to add more intel to the code. It helps in providing an insight to what the creator of the code, was thinking while writing it. It is also useful for providing some pointers or addendum related to the code. Comments overall help in reducing the complexity of the code, by being a sort of human-readable form of code. They also help to guide readers, who are unaware of the language. 
For Example, let’s take a look at the following code snippet:

@echo off

echo %~f0
echo %~t0

To someone who has never seen the aforementioned syntax, the code may be quite cryptic at first. But if comments are added to the code:

REM Used to disable echo of command entry and current working directory
@echo off

REM Displaying the full path (absolute Path) of this file
echo %~f0

REM Displaying the timestamp of creation of this file
echo %~t0

The code becomes clear on its functionality, and one can easily guide through its workings. 

Creating Inline Comments : 
Inline comments can be created by using the REM command at the beginning of the line and then typing in the comment. 
For example,

REM This code will display hello world
echo hello world!

Inline comments could also be added to the end of the line (preceded by some code) by using the & REM construct. 
For example,

echo Hello World! & REM This code will display hello world

Creating Multiline Comments : 
Multiline comments can be created by using multiple rem commands, that span several lines. 
For example,

REM This code will tell the current time
REM The resolution of the time will be until milliseconds
REM The time will be based on the current timezone
echo | time

Note – 
Comment creation exists through various other means as well. Ex. There exists other types of ~comments which allows for comments in between a statement. But they are not the documented way of commenting code, and exists due to workaround of other commands/syntaxs. Also, those are outside the scope of this article.

Last Updated :
04 Apr, 2023

Like Article

Save Article

  • Комета браузер скачать бесплатно для windows 7
  • Комп не видит динамики что делать windows 10
  • Комбинация чтобы выключить компьютер windows 10
  • Комбинация клавиш яркость экрана windows 10
  • Комбинация клавиш сон windows 10