What is echo command in windows

Команда 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 :

What is echo command in windows

Applies To: Windows Vista, Windows Server 2008, Windows Server 2012, Windows 8

Displays messages or turns on or off the command echoing feature. If used without parameters, echo displays the current echo setting.

For examples of how to use this command, see Examples.

Syntax

Parameters

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В Message 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В Message commands after the echo off command in your batch program.

Читайте также:  Rivatuner для windows 10 x64

When echo is turned off, the command prompt does not 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 do not affect the setting at the command prompt.

To prevent echoing a particular command in a batch file, insert an at 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 ( ) when you are using echo, use a caret (^) immediately before the pipe or redirection character (for example, ^|, ^>, or ^ echo is turned off, the command prompt does not 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 (вывод на экран) 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):

What is echo command in windows

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):

What is echo command in windows

Display messages on screen, turn command-echoing on or off.

Type ECHO without parameters to display the current echo setting (ON or OFF).

In most batch files you will want ECHO OFF, turning it ON can be useful when debugging a problematic batch script.

In a batch file, the @ symbol at the start of a line is the same as ECHO OFF applied to the current line only.

Normally a command is executed and takes effect from the next line onwards, @ is a rare example of a command that takes effect immediately.

Escape Command characters

Command characters will normally take precedence over the ECHO statement
e.g. The redirection and pipe characters: & | ON OFF

To override this behaviour you can escape each command character with ^ or : as follows:

An alternative approach is to use SET /P which will display the string without interpreting anything.

Echo text into a FILE

The general syntax is:
Echo This is some Text > FileName.txt

To avoid extra spaces:
Echo Some more text>FileName.txt

To create an empty (zero byte) file:
Echo. 2>EmptyFile.txt

Echo a Variable

To display a department variable:

A more robust alternative is to separate with : instead of a space.

Using a colon like this will sanitise the values ON /OFF /? so for example

Set _var=OFF
Echo %_var%
Will will actually turn Echo off

Echo:%_var%
Will simply display «OFF»

Using Echo: in this way does have some limitations:

  • If the variable does not exist, ECHO: will return the variable name» %_var% «
  • If you are using DelayedExpansion ( !_var! ) AND the syntax to search and replace parts of a variable or display substrings of a variable, then the Echo: syntax will not work. You can workaround this by using an intermediate variable or just reverting to the default parse time expansion of variables.

Echo a file

Echo a sound

The following command in a batch file will trigger the default beep on most PC’s

To type the BELL character use Ctrl-G or ‘Alt’ key, and 7 on the numeric keypad. (ascii 7)

The default beep is now played through the speakers/audio system, however if you select the ‘No Sounds’ scheme in Contol Panel > Sounds > Change system sounds, then the default beep will not play.

Alternatively using Windows Media Player:
START/min «C:\Program Files\Windows Media Player\wmplayer.exe» %windir%\media\chimes.wav

Echo a blank line

To produce an empty line, (without displaying the echo status) follow the Echo command with a colon or period character:
Echo:
or
Echo.
The last of those options Echo. can be troublesome because Echo. will search for a file named «echo» if the file is found that raises an error. If the ‘echo’ file does not exist then the command does work, but this still makes Echo. slightly slower than echo:
In theory other command delimiters are available but most have buggy side effects when used for this.

To ECHO text without including a CR/LF (source)

Echo text into a stream

Streams allow one file to contain several separate forks of information (like the macintosh resource fork)

The general syntax is:

Only the following commands support the File:Stream syntax — ECHO, MORE, FOR

Displaying streams:

A data stream file can be successfully copied and renamed despite the fact that most applications and commands will report a zero length file. The file size can be calculated from remaining free space. The file must always reside on an NTFS volume.

ECHO does not set or clear the Errorlevel.
ECHO is an internal command.

“The only thing that helps me pass the time away; is knowing I’ll be back at Echo Beach some day”

Читайте также:  Утилиты синий экран смерти windows
Оцените статью