Команда ECHO — вывод текста на экран консоли
Команда ECHO наверно является одной из самых простых и самых используемых команд. Применяется для вывода текстовых сообщений на стандартный вывод и для переключения режима отображения команд на экране.
Формат командной строки:
ECHO [ON | OFF] — включить / выключить режим отображения вводимых команд на экране.
ECHO [сообщение] отобразить текст сообщения на экране.
ECHO — при вводе команды без параметров, отображается текущий режим отображения команд:
Режим вывода команд на экран (ECHO) включен.
Для вывода пустой строки, используется команда ECHO с точкой:
echo Hello World. — вывод сообщения Hello World. на экран.
echo %USERNAME% — вывод на экран значения переменной окружения USERNAME (имени текущего пользователя)
Наиболее распространено использование команды echo в командных файлах. Практически любой командный файл начинается командой
@echo off — отключить режим вывода команд на экран. Символ @ перед командой echo используется для того, чтобы на экран не выводился и текст самой команды.
Очень часто команда echo используется для записи сообщений в текстовый файл с использованием перенаправлением вывода:
echo Начало работы — %DATE% в %TIME% >logfile.txt
Echo ERORLEVEL=%ERRORLEVEL% >> logfile.txt
Echo Конец работы, %DATE% в %TIME% >>logfile.txt
В текстовый файл logfile.txt записывается дата и время начала работы командного файла, некоторые результаты и время завершения.
Нередко, команда echo используется для создания нового файла:
echo 1 >newfile.cmd — вывести символ «1» в файл newfile.cmd . Если такого файла не существует, он будет создан, если существует, то будет перезаписан.
Значения параметров командной строки, переменных и их подстановочных значений, также нередко отображаются с помощью команды echo . Пример командного файла, выводящего на экран информацию о себе:
@echo off
ECHO ОБРАБАТЫВАЕТСЯ ФАЙЛ — %0
ECHO Дата/время создания/изменения командного файла — %
t0
ECHO Путь командного файла — «%
f0″
ECHO Диск командного файла — %
d0
ECHO Каталог командного файла — «%
p0″
ECHO Имя командного файла — %
n0
ECHO Расширение командного файла — %
x0
ECHO Короткое имя и расширение — %
s0
ECHO Атрибуты командного файла — %
a0
ECHO Размер командного файла — %
При выводе служебных символов, интерпретируемых командным процессором нужно использовать символ ^ . Например, вместо значения переменной ERRORLEVEL, нужно вывести текст “%ERRORLEVEL%”
ECHO ^%ERRORLEVEL^% = %ERRORLEVEL%
Особенностью команды ECHO является добавление служебных символов возврата каретки и перевода строки 0x0D и 0x0A (Carriage Return и Line Feed) в конец выводимого текста. Командный файл следующего содержания выводит текст из 3-х строк:
Если же требуется вывести весь текст в одну строку, обычно используют эмуляцию команды ECHO командой SET с параметром /P, используемой для организации диалога с пользователем, когда выводится сообщение, на которое требуется ответ. Выводимое сообщение можно использовать таким же образом, как и в команде ECHO, а вместо ответа можно использовать ввод с фиктивного устройства nul :
При выполнении такого командного файла сообщение на экране будет представлено одной строкой:
Для подачи звуковых сигналов можно использовать вывод служебного символа с кодом 07 (BELL). Достаточно просто включить его в поток выходных данных, что зависит от возможностей редактора, который используется для написания командного файла. Можно использовать и стандартные возможности командной строки, добавив комбинацию CTRL+G :
echo (вывод на экран) echo
Отображает сообщения или включает или отключает функцию вывода команд. Displays messages or turns on or off the command echoing feature. При использовании без параметров echo отображает текущее значение эха. If used without parameters, echo displays the current echo setting.
Синтаксис Syntax
Параметры Parameters
Параметр Parameter | Описание Description |
---|---|
[вкл. | Откл.] [on | off] | Включает или выключает функцию вывода команд. Turns on or off the command echoing feature. Команда по умолчанию включена. Command echoing is on by default. |
Задает текст, отображаемый на экране. Specifies the text to display on the screen. | |
/? /? | Отображение справки в командной строке. Displays help at the command prompt. |
Комментарии Remarks
echo Команда особенно полезна при отключенном эхо . The echo command is particularly useful when echo is turned off. Чтобы отобразить сообщение, которое содержит несколько строк без отображения команд, можно включить несколько echo команд после команды echo off в пакетной программе. To display a message that is several lines long without displaying any commands, you can include several echo commands after the echo off command in your batch program.
После выключения эхо Командная строка не отображается в окне командной строки. After echo is turned off, the command prompt doesn’t appear in the Command Prompt window. Чтобы отобразить командную строку, введите команду echo on. To display the command prompt, type echo on.
Если используется в пакетном файле, Включение и вывод не влияют на параметр в командной строке. If used in a batch file, echo on and echo off don’t affect the setting at the command prompt.
Чтобы предотвратить вывод определенной команды в пакетном файле, вставьте @ знак перед командой. To prevent echoing a particular command in a batch file, insert an @ sign in front of the command. Чтобы предотвратить вывод всех команд в пакетном файле, включите команду echo off в начале файла. To prevent echoing all commands in a batch file, include the echo off command at the beginning of the file.
Чтобы отобразить символ канала ( | ) или перенаправления ( или > ) при использовании эха, используйте знак крышки ( ^ ) непосредственно перед символом канала или перенаправления. To display a pipe ( | ) or redirection character ( or > ) when you are using echo, use a caret ( ^ ) immediately before the pipe or redirection character. Например,, ^| ^> или ^ ). For example, ^| , ^> , or ^ ). Чтобы отобразить курсор, введите две крышки подряд ( ^^ ). To display a caret, type two carets in succession ( ^^ ).
Примеры Examples
Чтобы отобразить текущее значение echo , введите: To display the current echo setting, type:
Чтобы вывести на экран пустую строку, введите: To echo a blank line on the screen, type:
Не включайте пробел перед точкой. Don’t include a space before the period. В противном случае вместо пустой строки отображается точка. Otherwise, the period appears instead of a blank line.
Чтобы запретить вывод команд в командной строке, введите: To prevent echoing commands at the command prompt, type:
Когда эхо отключено, Командная строка не отображается в окне командной строки. When echo is turned off, the command prompt doesn’t appear in the Command Prompt window. Чтобы снова отобразить командную строку, введите команду echo on. To display the command prompt again, type echo on.
Чтобы предотвратить отображение на экране всех команд в пакетном файле (включая команду echo off ), в первой строке типа пакетного файла: To prevent all commands in a batch file (including the echo off command) from displaying on the screen, on the first line of the batch file type:
Команду echo можно использовать как часть оператора If . You can use the echo command as part of an if statement. Например, чтобы найти в текущем каталоге любой файл с расширением. rpt и вывести сообщение при обнаружении такого файла, введите: For example, to search the current directory for any file with the .rpt file name extension, and to echo a message if such a file is found, type:
Следующий пакетный файл выполняет поиск файлов с расширением txt в текущем каталоге и выводит сообщение с указанием результатов поиска: The following batch file searches the current directory for files with the .txt file name extension, and displays a message indicating the results of the search:
Если при выполнении пакетного файла не найдены TXT-файлы, отображается следующее сообщение: If no .txt files are found when the batch file is run, the following message displays:
Если TXT-файлы найдены при запуске пакетного файла, отображаются следующие выходные данные (в этом примере предполагается, что файлы File1.txt, File2.txt и File3.txt существуют): If .txt files are found when the batch file is run the following output displays (for this example, assume the files File1.txt, File2.txt, and File3.txt exist):
Windows echo in file
Displays messages or turns on or off the command echoing feature. If used without parameters, echo displays the current echo setting.
Syntax
Parameters
Parameter | Description |
---|---|
[on | off] | Turns on or off the command echoing feature. Command echoing is on by default. |
Specifies the text to display on the screen. | |
/? | Displays help at the command prompt. |
Remarks
The echo command is particularly useful when echo is turned off. To display a message that is several lines long without displaying any commands, you can include several echo commands after the echo off command in your batch program.
After echo is turned off, the command prompt doesn’t appear in the Command Prompt window. To display the command prompt, type echo on.
If used in a batch file, echo on and echo off don’t affect the setting at the command prompt.
To prevent echoing a particular command in a batch file, insert an @ sign in front of the command. To prevent echoing all commands in a batch file, include the echo off command at the beginning of the file.
To display a pipe ( | ) or redirection character ( or > ) when you are using echo, use a caret ( ^ ) immediately before the pipe or redirection character. For example, ^| , ^> , or ^ ). To display a caret, type two carets in succession ( ^^ ).
Examples
To display the current echo setting, type:
To echo a blank line on the screen, type:
Don’t include a space before the period. Otherwise, the period appears instead of a blank line.
To prevent echoing commands at the command prompt, type:
When echo is turned off, the command prompt doesn’t appear in the Command Prompt window. To display the command prompt again, type echo on.
To prevent all commands in a batch file (including the echo off command) from displaying on the screen, on the first line of the batch file type:
You can use the echo command as part of an if statement. For example, to search the current directory for any file with the .rpt file name extension, and to echo a message if such a file is found, type:
The following batch file searches the current directory for files with the .txt file name extension, and displays a message indicating the results of the search:
If no .txt files are found when the batch file is run, the following message displays:
If .txt files are found when the batch file is run the following output displays (for this example, assume the files File1.txt, File2.txt, and File3.txt exist):
Echo a blank (empty) line to the console from a Windows batch file [duplicate]
When outputting status messages to the console from a Windows batch file, I want to output blank lines to break up the output. How do I do this?
3 Answers 3
Any of the below three options works for you:
Note: Though my original answer attracted several upvotes, I decided that I could do much better. You can find my original (simplistic and misguided) answer in the edit history.
If Microsoft had the intent of providing a means of outputting a blank line from cmd.exe , Microsoft surely would have documented such a simple operation. It is this omission that motivated me to ask this question.
So, because a means for outputting a blank line from cmd.exe is not documented, arguably one should consider any suggestion for how to accomplish this to be a hack. That means that there is no known method for outputting a blank line from cmd.exe that is guaranteed to work (or work efficiently) in all situations.
With that in mind, here is a discussion of methods that have been recommended for outputting a blank line from cmd.exe . All recommendations are based on variations of the echo command.
While this will work in many if not most situations, it should be avoided because it is slower than its alternatives and actually can fail (see here, here, and here). Specifically, cmd.exe first searches for a file named echo and tries to start it. If a file named echo happens to exist in the current working directory, echo. will fail with:
At the end of this answer, the author argues that these commands can be slow, for instance if they are executed from a network drive location. A specific reason for the potential slowness is not given. But one can infer that it may have something to do with accessing the file system. (Perhaps because : and \ have special meaning in a Windows file system path?)
However, some may consider these to be safe options since : and \ cannot appear in a file name. For that or another reason, echo: is recommended by SS64.com here.
This lengthy discussion includes what I believe to be all of these. Several of these options are recommended in this SO answer as well. Within the cited discussion, this post ends with what appears to be a recommendation for echo( and echo: .
My question at the top of this page does not specify a version of Windows. My experimentation on Windows 10 indicates that all of these produce a blank line, regardless of whether files named echo , echo+ , echo, , . echo] exist in the current working directory. (Note that my question predates the release of Windows 10. So I concede the possibility that older versions of Windows may behave differently.)
In this answer, @jeb asserts that echo( always works. To me, @jeb’s answer implies that other options are less reliable but does not provide any detail as to why that might be. Note that @jeb contributed much valuable content to other references I have cited in this answer.
Conclusion: Do not use echo. . Of the many other options I encountered in the sources I have cited, the support for these two appears most authoritative:
But I have not found any strong evidence that the use of either of these will always be trouble-free.