Batch-file Echo

Echo

Синтаксис

echo [{on|off}] [сообщение]

Параметры

{on|off}
Включение или отключения режима отображения на экране информации о работе команд.
сообщение
Задание текста для вывода на экран.
/?
Отображение справки в командной строке.

Примеры

Следующий пример представляет собой пакетный файл, выводящий сообщение из трех строк на
экран с пустыми строками до и после него:

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

При выводе русских букв необходимо помнить о кодировке.
Текст сообщения должен быть в DOS (866) кодировке.
Многие текстовые редакторы его поддерживают.
Если необходимо, что бы текст сообщений был в WIN (1251)
кодировке и был виден из любого редактора, то можно
использовать следующий прием.

Такие сообщения для удобства можно выделить в отдельный блок.

Если такой блок неудобно располагать в начале файла, то можно
образовать из него процедуру, разместить в конце bat файла,
а на исполнение вызвать эту процедуру командой call в начале bat файла.
Из примера все должно стать понятнее))

Если сообщение одиночное, то можно
поступить следующим образом:

Для вопросов, обсуждений, замечаний, предложений и т. п. можете использовать
раздел форума
этого сайта (требуется регистрация).

Послал Сообщение

healer

Администратор

Из: Москва
Сообщения: 24399

Batch-file 
 Echo Вывод русского текста из команд bat / cmd

Послано: 18-05-2015 10:54

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

~~~~~~~~~~~~

Здоровья Вам. Духовного и физического.


healer

Администратор

Из: Москва
Сообщения: 24399

Batch-file 
 Echo Вывод русского текста из команд bat / cmd

Послано: 18-05-2015 10:58

При выводе русских букв необходимо помнить о кодировке.
Текст сообщения т.е сам bat / cmd должен быть в DOS (866) кодировке.
Многие текстовые редакторы его поддерживают.
Однако это не всегда удобно.

Раасмотрим необходимые действия если необходимо, что бы кодировка самого bat / cmd файла была в WIN (1251) и при этом корректно выводить русские буквы, например, командой echo.

~~~~~~~~~~~~

Здоровья Вам. Духовного и физического.


healer

Администратор

Из: Москва
Сообщения: 24399

Batch-file 
 Echo Вывод русского текста из команд bat / cmd

Послано: 19-05-2015 06:02

Для смены кодировок есть команда chcp и, казалось бы такой код приведет к желаемому результату

rem НЕ ВЕРНО
chcp 1251 >NUL
title Русский текст
chcp 866 >NUL
pause

Результат разочарует.

~~~~~~~~~~~~

Здоровья Вам. Духовного и физического.


healer

Администратор

Из: Москва
Сообщения: 24399

Batch-file 
 Echo Вывод русского текста из команд bat / cmd

Послано: 19-05-2015 06:46

Но не все так густно.
Внесем небольшие изменения в пример, приведенный выше

chcp 1251 >NUL
set x=Не ждите чуда, чудите сами
chcp 866 >NUL
title %x%
pause

Теперь русские буквы отразятся корректно.

~~~~~~~~~~~~

Здоровья Вам. Духовного и физического.


healer

Администратор

Из: Москва
Сообщения: 24399

Batch-file 
 Echo Вывод русского текста из команд bat / cmd

Послано: 19-05-2015 06:49

Аналогично команде title из предыдущего примера можно использовать команду echo.
Что бы каждый раз не переключать кодировки удобно такие сообщения собрать в блок.

chcp 1251 >NUL
set MSG01=Отсутствует исходный файл
set MSG02=Ошибка копирования
set MSG03=Успешное завершение программы
set TIT=Копирование файла
chcp 866 >NUL
Title %TIT%
….
echo %MSG01%
….
echo %MSG02%
….
echo %MSG03%

~~~~~~~~~~~~

Здоровья Вам. Духовного и физического.


healer

Администратор

Из: Москва
Сообщения: 24399

Batch-file 
 Echo Вывод русского текста из команд bat / cmd

Послано: 19-05-2015 07:01

Если такой блок получается достаточно большой, то, как мне кажется, не очень нагляно оставлять его в начале файла.
В таком случае можно из такого болка образовать процедуру, разместить в конце bat файла, а на исполнение вызвать эту процедуру командой call в начале bat файла. Из примера все должно стать понятнее))

….
call :blockmsg

Title %TIT%
….
echo %MSG01%
….
echo %MSG02%
….
echo %MSG03%
….
exit

:blockmsg
chcp 1251 >NUL
set MSG01=Отсутствует исходный файл
set MSG02=Ошибка копирования
set MSG03=Успешное завершение программы
set TIT=Копирование файла
chcp 866 >NUL
exit /b

~~~~~~~~~~~~

Здоровья Вам. Духовного и физического.


healer

Администратор

Из: Москва
Сообщения: 24399

Batch-file 
 Echo Вывод русского текста из команд bat / cmd

Послано: 19-05-2015 07:07

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

chcp 1251 >nul
for /f “delims=” %%A in (“Отойдите на безопасное расстояние”) do >nul chcp 866& echo.%%A

~~~~~~~~~~~~

Здоровья Вам. Духовного и физического.


healer

Администратор

Из: Москва
Сообщения: 24399

Batch-file 
 Echo Вывод русского текста из команд bat / cmd

Послано: 21-08-2015 06:08

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

~~~~~~~~~~~~

Здоровья Вам. Духовного и физического.


healer

Администратор

Из: Москва
Сообщения: 24399

Batch-file 
 Echo Вывод русского текста из команд bat / cmd

Послано: 21-08-2015 06:23

call :blockmsg

del /Q “%fname01%”
del /Q “%fname02%”
del /Q “%fname03%”
del /Q “%fname04%”

exit

:blockmsg
chcp 1251 >NUL
set fname01=c:\Documents and Settings\Ivanov\Рабочий стол\Справочник БИК (новый).lnk
set fname02=c:\Documents and Settings\Ivanov\Рабочий стол\Справочник БИК.lnk
set fname03=c:\Documents and Settings\Ivanov\Рабочий стол\Вестник Банка России.lnk
set fname04=c:\Documents and Settings\Ivanov\Рабочий стол\Справочники.lnk

chcp 866 >NUL
exit /b

~~~~~~~~~~~~

Здоровья Вам. Духовного и физического.

Вывод на экран сообщения или задание режима вывода на экран сообщений команд. Вызванная
без параметров команда echo выводит текущий режим.

Синтаксис

echo [{on|off}] [сообщение]

Параметры

{on|off}
Включение или отключения режима отображения на экране информации о работе команд.
сообщение
Задание текста для вывода на экран.
/?
Отображение справки в командной строке.

Примеры

Следующий пример представляет собой пакетный файл, выводящий сообщение из трех строк на
экран с пустыми строками до и после него:

При выводе русских букв необходимо помнить о кодировке.
Текст сообщения должен быть в DOS (866) кодировке.
Многие текстовые редакторы его поддерживают.
Если необходимо, что бы текст сообщений был в WIN (1251)
кодировке и был виден из любого редактора, то можно
использовать следующий прием.

Такие сообщения для удобства можно выделить в отдельный блок.

Если такой блок неудобно располагать в начале файла, то можно
образовать из него процедуру, разместить в конце bat файла,
а на исполнение вызвать эту процедуру командой call в начале bat файла.
Из примера все должно стать понятнее))

Если сообщение одиночное, то можно
поступить следующим образом:

Для вопросов, обсуждений, замечаний, предложений и т. п. можете использовать
раздел форума
этого сайта (требуется регистрация).

Новый раздел о средствах командной строки в рамках этого же проекта расположен
здесь

Хотелось бы узнать, каким способом в файлах с расширением .bat можно писать русским языком без иероглифов?

Nicolas Chabanovsky's user avatar

задан 12 янв 2012 в 16:40

I'm so sorry's user avatar

I’m so sorryI’m so sorry

2791 золотой знак2 серебряных знака18 бронзовых знаков

0

chcp 1251
echo тест
pause

Только шрифт консоли нужно поменять на Lucida Console или Consolas

ответ дан 12 янв 2012 в 19:03

insolor's user avatar

insolorinsolor

:/>  Как зайти в реестр Windows 10/8/7/XP? (Видео) | IT-уроки

45.5k15 золотых знаков54 серебряных знака94 бронзовых знака

1

Файлы создаются в кодировке cp866, поэтому надо задавать charset=cp866.

Nicolas Chabanovsky's user avatar

ответ дан 12 янв 2012 в 16:43

vv-d's user avatar

3

Мне помогло следующее решение:

chcp 65001
echo тест
pause

ответ дан 28 авг 2019 в 5:24

Vitaliy's user avatar

Вообще, вот отличная таблица современных кодировок для виндового терминала.

Так, chcp с параметром 1251 поставит русскую кодировку, т.е CP1251(Windows-1251), а
с параметром 65001 – интернациональную кодировку UTF-8.

ответ дан 23 июн 2012 в 19:30

Free_man's user avatar

Free_manFree_man

9604 золотых знака14 серебряных знаков22 бронзовых знака

Вам надо NotePad++. Потому что если поменять кодировку например на OEM 866 и напишите в батнике @chcp 866 то он будет понимать русский язык. Так работает даже если вы поменяете OEM 866 на OEM 855 и @chcp 866 на @chcp 855. (Цифры должны быть одинаковыми). У меня так работает 🙂

ответ дан 11 окт 2022 в 18:11

user523190's user avatar

echo "abcd ę" > out.txt

(the batch file is encoded with UTF-8)

If it’s not possible, then can I change the encoding of the text file after creating it?
Is there any tool in the gnuwin32 package that can help me to change the encoding?

Martin Prikryl's user avatar

asked Aug 14, 2012 at 23:14

BearCode's user avatar

Use chcp command to change active code page to 65001 for utf-8.

chcp 65001

answered Aug 2, 2015 at 9:18

cuixiping's user avatar

8 gold badges81 silver badges93 bronze badges

Try starting CMD.exe with the /U switch: it causes all pipe output to be Unicode instead of ANSI.

answered Aug 14, 2012 at 23:28

Garrett's user avatar

answered Nov 22, 2017 at 15:29

bcag2's user avatar

1 gold badge15 silver badges31 bronze badges

The problem was that the file contained the line:

<META content="text/html; charset=iso-8859-2" http-equiv=Content-Type> 

and then Notepad2 and Firefox was changing the charset, showing Ä instead of ę. In plain Notepad, the file looks ok.
The solution was to add the UTF-8 signature (Byte Order Mark) at the beginning of the file:

echo1 -ne \xEF\xBB\xBF > out.htm

thanks for the answers

Uwe Keim's user avatar

56 gold badges176 silver badges290 bronze badges

answered Aug 17, 2012 at 5:07

BearCode's user avatar

6 gold badges34 silver badges37 bronze badges

answered Mar 26, 2019 at 23:09

whiterabbit's user avatar

I'm not sure if this is the answer you are looking for or if it's already been answered for you... 
I'd use the catet character ( ^ ) in a batch file and output to a file using escape character ^. See examples..
Desired output...
<META content="text/html; charset=iso-8859-2" http-equiv=Content-Type> 

Replace code with this: 
Example 1: echo ^<META content="text/html; charset=iso-8859-2" http-equiv=Content-Type^> 
Example 2: echo ^<?xml version="1.0" encoding="utf-8" ?^>

answered Jan 12 at 17:39

Robert Maarschalkerweerd's user avatar

В данной статье пойдёт речь о кодировках в Windows. Все в жизни хоть раз использовали и писали консольные приложения как таковые. Нету разницы для какой причины. Будь-то выбивание процесса или же просто написать «Привет!!! Я не могу сделать кодировку нормальной, поэтому я смотрю эту статью!».

Тем, кто ещё не понимает, о чём проблема, то вот Вам:

image

А тут было написано:

echo Я абракадабра, написанная автором.

Но никто ничего не понял.

В любом случае в Windows до 10 кодировка BAT и других языков, не использует кодировку поддерживающую Ваш язык, поэтому все русские символы будут писаться неправильно.

1. Настройка консоли в батнике

Сразу для тех, кто пишет chcp 1251 лучше написать это:

assoc .bat = .mp4

Первый способ устранения проблемы, это Notepad++. Для этого Вам нужно открыть Ваш батник таким способом:

image

Не бойтесь, у Вас откроется код Вашего батника, а затем Вам нужно будет сделать следующие действия:

image

Если Вам ничего не помогло, то преобразуйте в UTF-8 без BOM.

2. Написание консольных программ
Нередко люди пишут консольные программы(потому что на некоторых десктопные писать невозможно), а кодировка частая проблема.

Первый способ непосредственно Notepad++, но а если нужно сначала одну кодировку, а потом другую?

Сразу для использующих chcp 1251 пишите это:

del C:\Program Data
echo Mne pofig
pause

Второй способ это написать десктопную программу, или же использовать Visual Studio. Если же не помогает, то есть первое: изменение кодировки вывода(Пример на C++).

#include <iostream>
#include <windows.h>
int main() {
SetConsoleCP(номер_кодировки);
SetConsoleOutputCP(номер_кодировки);
}

Если же не сработает:

#include <math.h> //Не забываем про библиотеку Math.
char bufRus[256];
 
char* Rus(const char* text) {
      CharToOem(text, bufRus);
      return bufRus
      }
int main {
    cout << "Тут пишите, что угодно!" << endl;
    system("pause")
    return 0
}

3. Изменение chcp 1251
Если же у Вас батник, то напишите в начало:

chcp 1251 >nul
for /f "delims=" %%A in ("Мой текст") do >nul chcp 866& echo.%%A

Теперь у Нас будет нормальный вывод в консоль. На других языках (С++):

SetConsoleOutputCP(1251) 
//А тут добавляете тот цикл, который был в батнике

4. Сделать жизнь мёдом
При использовании данного способа Вы не сможете:

  • Разрабатывать приложения на Windows ниже 10
  • Спасти мир от данной проблемы
  • Думать о других людях
  • Разрабатывать десктопные приложения, так как Вам жизнь покажется мёдом
  • Сменить Windows на версию ниже 10
  • Ну и понимать людей, у которых Windows ниже 10

Установить Windows 10. Там кодировка консоли специально подходит для языка страны, и Вам больше не нужно будет беспокоиться об этой проблеме. Но у Вас появится ещё 6 проблем, и вернуться к предыдущей лицензионной версии Windows Вы не сможете.

В данной статье пойдёт речь о кодировках в Windows. Все в жизни хоть раз использовали и писали консольные приложения как таковые. Нету разницы для какой причины. Будь-то выбивание процесса или же просто написать «Привет!!! Я не могу сделать кодировку нормальной, поэтому я смотрю эту статью!».

Тем, кто ещё не понимает, о чём проблема, то вот Вам:

image

А тут было написано:

echo Я абракадабра, написанная автором.

Но никто ничего не понял.

В любом случае в Windows до 10 кодировка BAT и других языков, не использует кодировку поддерживающую Ваш язык, поэтому все русские символы будут писаться неправильно.

1. Настройка консоли в батнике

Сразу для тех, кто пишет chcp 1251 лучше написать это:

assoc .bat = .mp4

Первый способ устранения проблемы, это Notepad++. Для этого Вам нужно открыть Ваш батник таким способом:

image

Не бойтесь, у Вас откроется код Вашего батника, а затем Вам нужно будет сделать следующие действия:

image

Если Вам ничего не помогло, то преобразуйте в UTF-8 без BOM.

2. Написание консольных программ
Нередко люди пишут консольные программы(потому что на некоторых десктопные писать невозможно), а кодировка частая проблема.

Первый способ непосредственно Notepad++, но а если нужно сначала одну кодировку, а потом другую?

Сразу для использующих chcp 1251 пишите это:

del C:\Program Data
echo Mne pofig
pause

Второй способ это написать десктопную программу, или же использовать Visual Studio. Если же не помогает, то есть первое: изменение кодировки вывода(Пример на C++).

#include <iostream>
#include <windows.h>
int main() {
SetConsoleCP(номер_кодировки);
SetConsoleOutputCP(номер_кодировки);
}

Если же не сработает:

#include <math.h> //Не забываем про библиотеку Math.
char bufRus[256];
 
char* Rus(const char* text) {
      CharToOem(text, bufRus);
      return bufRus
      }
int main {
    cout << "Тут пишите, что угодно!" << endl;
    system("pause")
    return 0
}

3. Изменение chcp 1251
Если же у Вас батник, то напишите в начало:

chcp 1251 >nul
for /f "delims=" %%A in ("Мой текст") do >nul chcp 866& echo.%%A

Теперь у Нас будет нормальный вывод в консоль. На других языках (С++):

SetConsoleOutputCP(1251) 
//А тут добавляете тот цикл, который был в батнике

4. Сделать жизнь мёдом
При использовании данного способа Вы не сможете:

  • Разрабатывать приложения на Windows ниже 10
  • Спасти мир от данной проблемы
  • Думать о других людях
  • Разрабатывать десктопные приложения, так как Вам жизнь покажется мёдом
  • Сменить Windows на версию ниже 10
  • Ну и понимать людей, у которых Windows ниже 10
:/>  Batch-script

Установить Windows 10. Там кодировка консоли специально подходит для языка страны, и Вам больше не нужно будет беспокоиться об этой проблеме. Но у Вас появится ещё 6 проблем, и вернуться к предыдущей лицензионной версии Windows Вы не сможете.

The echo Command in Batch

Use the echo Command in Batch

The echo command is an internal command used to print out the text on the screen or turn on or off the command-echoing. It does not set the errorlevel or clear the errorlevel.

Every command executed on running a batch file is shown on the command line along with the output. When we run a batch file, all the commands are executed line by line in a sequential manner.

Using the echo command, we can turn off the echoing of the commands in the command prompt even with the echo command itself.

Syntax:

echo [on | off]
echo <message>
echo /?
  • on – display commands along with the output.
  • off – hides the commands and only displays the output.
  • message – text to be printed.

If you type echo without any parameters or options, it will show the status of the echo command(i.e., on or off). In Batch files, it is mostly used to turn off the command’s echoing and only show the output, and the echo on command is useful while debugging a batch file.

To check the status of the echo command or echo setting, execute the following command in the command prompt.

Output:

check status of echo

To turn off the echoing of the command, add echo off at the top of your Batch file.

echo off

Output:

echo off output

However, the above command will show the line echo off in the command prompt. To hide this line, add @ at the start of the echo off.

turn off echoing along with echo command

Output:

turn off echoing along with echo command - output

Use the echo Command to Print Message

print a message using echo command

print a message using echo command - output


echo on and off in same batch file

echo on and off in same batch file - output

Echo a New Line or Blank Line in a Batch File

Example – 1:

add a blank line using echo

Example – 2:

add a blank line using echo - method 2

add a blank line using echo - output

Echo Text Into a File

echo text to a file

create an empty file using echo command

Use the echo Command to Echo a Variable

echo a variable

Example – 1:

echo a set variable

echo a set variable - output

Example – 2:

echo a set variable - method 2

echo a set variable method 2 - output

Echo the System Path

echo system path

echo system path - output

Use the echo Command With Escape Command Characters

When you use the echo command along with the command characters, like the redirection(&) and pipe(|, on, off) characters, the command character will by default precede the echo command. To avoid this, we need to use the escape characters(:, ^) whenever the command characters are used.

Add the escape character before the command character for each command character separately.

@echo off
ECHO Here, the escape character is used for the ^& character like Mickey ^& Mouse
ECHO file1 ^| file2 ^| file3

escape command characters using echo command

Output:

escape command characters using echo command - output

Conclusion

We have discussed the echo command and covered almost everything, along with examples. It is a very useful command used in Batch files for various reasons, as explained in the examples above.

Any of the below three options works for you:

echo[

echo(

echo. 
@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo( 
echo The above line is also blank.
echo. 
echo The above line is also blank.

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.


echo.
'echo.' is not recognized as an internal or external command,
operable program or batch file.

echo:
echo\

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


echo(
echo+
echo,
echo/
echo;
echo=
echo[
echo]

echo(
echo:

But I have not found any strong evidence that the use of either of these will always be trouble-free.


@echo off
echo Here is the first line.
echo(
echo There is a blank line above this line.
Here is the first line.

There is a blank line above this line.

I agree that a file called “echo” MAY cause problems,

but feel it is inappropriate for DosTips to needlessly punish an innocent user of a batch script that happens to visit a multiplicity of folders to purge junk that was left behind when a security program was removed.

After installing Comodo Firewall I ran a user forum supplied script to remove many remnants that were typically left behind, BUT due to permissions issues I spotted the odd “Access is denied” and “cannot access” within the screens of output messages as CD and DEL and REG.EXE commands flooded my monitor, but no clue upon which command / target was responsible. The script aimed CD at a directory that was often not present, but ignored the error and proceeded to delete any files with “target” names that happened to be in its previous CD location. It also ignored “Access is denied” and “cannot access” messages. I inserted ECHO ON in various places to track down the command / targets giving problems, and then I took ownership and resolved the permissions problems. The original script ignored all errors, and a few VITAL “access” errors were totally obscured by the flood of so many perfectly VALID “error” messages, e.g. :-

The system cannot find the path specified.

Could Not Find …

Error: The system was unable to find the specified registry key or value.

I ran that user script 12 times in 25 minutes whilst identifying and fixing permission issues. When I finally succeeded with a sigh of relief I rebooted and then checked the event log for errors.

There was some problem with recovery on 4 off .NET framework files upon the first reboot, but further reboots appeared error free.

I subsequently found that …\System32\wbem\AutoRecover had increased from the 10 off *.MOF files accumulated during the 5 year life of the P.C. to 54 files. I am concerned that in 25 minutes that script with no error checking has now added another 22 years worth of degradation to my P.C. – and .NET Framework was bad enough before all this ! ! !

:/>  Список основных команд оболочки bash в Linux 🅱️

I now believe that the original script corrupted Catroot which has now been rebuilt, BUT AutoRecovery still holds 54 *.MOF files and I have asked on 6 forums but no-one has given definitive guidance upon whether the corruption has been cured or masked.

I have decided to restore the drive C:\ image I captured BEFORE I removed Comodo, and avoid all errors as I make a second attempt.

For my second attempt I have revised the original script with all output and error messages redirected to error checking that suppresses all “not present” types of indications, and only displays the “permission failure” types of errors.

I was disappointed that my final test run of my script included the spurious

“‘echo.’ is not recognized as an internal or external command,

operable program or batch file.”

This error was only when deleting files from one specific directory that happened to have a file named “ECHO”. This error was produced by only one of a large number of “ECHO.” command with which I was documenting the progress of the script. This error only happened upon the first run of the script within a DOS shell – subsequent runs had no such error. I only saw an error because of my extreme care.

It took me a few hours to identify and cure the problem.

To avoid any future problems I will never again use “ECHO.” for a blank line.

I suggest it would be a kindness to forum members if the unreliable “ECHO.” be replaced with anything else (such as ECHO/) to avoid punishing them for the presence of a naughty ECHO file that they never knew about.

Technically, ECHO. is a serious waste of CPU cycles.

My experience demonstrates that when file ECHO exists in the current directory the script will try to execute that file. This implies that if the file ECHO exists ANYWHERE on the %PATH% it will be executed.

WORSE, even if there is no such file, when the script encounters “ECHO.” it will not immediately print the blank line, but will first trawl through every directory that is on the %PATH% to see if there is an ECHO to execute.

For the last 30 years I have designed Real Time security systems with 8 bit processors. My focus has been to ensure continuous unstoppable error free operation, and efficiency of code in a limited address space. I ensured the code was correct, and that it had dependable fail-safe mechanisms for dealing with the unexpected.

Windows has been a bitter pill to swallow now that I am retired.

The presence of a file named “ECHO” was unexpected, but should now be no surprise, and I feel that once an unexpected error mechanism has been identified it should be avoided.

Regards

Alan

Introduction

echo can be used to control and produce output.

Syntax

  • ECHO [ON | OFF]
  • ECHO message
  • ECHO(message
  • ECHO(

Parameters

  • echo. will also display an empty string. However, this is slower than echo( as echo. will search for a file named “echo”. Only if this file does not exist will the command work, but this check makes it slower.
  • echo: will behave just like echo(, unless message looks like a file path, e.g. echo:foo\..\test.bat. In this case, the interpreter will see echo:foo as a folder name, strip echo:foo\..\ (because it appears just to enter the directory echo:foo then leave it again) then execute test.bat, which is not the desired behaviour.

Displaying Messages

To display “Some Text”, use the command:

echo Some Text

To display the strings On and Off (case insensitive) or the empty string, use a ( instead of white-space:

echo(ON
echo(
echo(off

This will output:

ON

off
<nul set/p=Some Text

Echo Setting

C:\Windows\System32>echo Hello, World!
Hello, World!

C:\Windows\System32>where explorer
C:\Windows\System32\explorer.exe

C:\Windows\System32>exit
Hello, World!
C:\Windows\System32\explorer.exe

Getting and Setting

> echo
ECHO is on.
> echo off

> echo
ECHO is off.

> echo on

> echo
ECHO is on.

Echo outputs everything literally

Quotes will be output as-is:

echo "Some Text"
"Some Text"

Comment tokens are ignored:

echo Hello World REM this is not a comment because it is being echoed!
Hello World REM this is not a comment because it is being echoed!
echo hello && echo world
hello
world

Echo output to file

echo. > example.bat (creates an empty file called "example.bat")

echo message > example.bat (creates example.bat containing "message")
echo message >> example.bat (adds "message" to a new line in example.bat)
(echo message) >> example.bat (same as above, just another way to write it)

Output to path

A little problem you might run into when doing this:

echo Hello how are you? > C:\Users\Ben Tearzz\Desktop\example.bat

(This will NOT make a file on the Desktop, and might show an error message)
echo Hello how are you? > "C:\Users\Ben Tearzz\Desktop\example.bat"
(This will make a file on MY Desktop)

But what if you want to make a file that outputs a new file?

echo message > file1.bat > example.bat

(This is NOT going to output:
"message > file1.bat" to example.bat

Then how do we do this?

echo message ^> file1.bat > example.bat

(This will output: 
"message > file1.bat" to example.bat

Same goes for other stuff in batch

set example="text"
echo %example% > file.bat
(This will output "text" to file.bat)

if we don’t want it to output “text” but just plain %example% then write:

echo ^%example^% > file.bat
(This will output "%example%" to file.bat)
else = ||
if ^%example^%=="Hello" echo True || echo False > file.bat

(This will output:
if %example%=="Hello" echo True

to output the whole line we write:

if ^%example^%=="Hello" echo True ^|^| echo False > file.bat

This will output:
if %example%=="Hello" echo True || echo False

If the variable is equal to “Hello” then it will say “True”, else it will say “False”

@Echo off

@echo off prevents the prompt and contents of the batch file from being displayed, so that only the output is visible. The @ makes the output of the echo off command hidden as well.

Turning echo on inside brackets

@echo off
(
    echo on
    echo ##
)
echo $$
@echo off
setlocal

:: echo on macro should followed by the command you want to execute with echo turned on
set "echo_on=echo on&for %%. in (.) do"

(
  %echo_on% echo ###
)

Оставьте комментарий