Echo

Работа с bat через «Блокнот»

Алгоритм создания

Процесс работы через «Блокнот» вовсе не сложный. Если вы раньше никогда этим не занимались, то вполне справитесь, узнав, как создать bat-файл и дополнять в нём команды. Начнём с создания. Здесь действуйте строго по алгоритму:

  1. Создаёте текстовый документ, он у вас первоначально получится с расширением txt. Произвести эту операцию можно несколькими способами, некоторые зависят от уровня установленной у вас Windows:
    • В папке, выбранной вами, кликнуть правой кнопкой на поле, откроется меню, там выбираем «Создать» — «Текстовый документ»;
    • Запустить «Блокнот» через «Пуск», выбрав «Все программы» — «Стандартные» — «Блокнот» (для Windows 7);
    • В поздних (после 7) версиях Windows открыть «Блокнот» можно также через «Пуск» : идёте через «Все приложения», далее «Стандартные» — «Windows» и там уже в списке выбирайте «Блокнот»;
    • Вызовите системное окно команд посредством комбинации Win+R, в строке введите «notepad», нажмите «Ok».
  2. Впишите текст команд. Для пробы запишите, например, «START taskmgr.exe» — запуск диспетчера задач . «START» говорит интерпретатору команд, что нужно запустить какую-либо программу, далее указывается экзешник программы.
  3. Укажите путь, где сохранить созданный документ.
  4. Указываете в окне сохранения:
    • в строке «Тип» — «Все файлы»;
    • в строке «Имя» вводите название и расширение bat, дописав его после названия, поставив точку между названием и расширением, — например, «file.bat».
  5. Кликаете на «Сохранить».

В указанной вами папке появится пакетный файл с расширением.bat.

Запуск файла

Открыть bat-файл проще, щёлкнув дважды по нему мышкой. Второй способ — запуск из командной строки: вводим адрес, где находится документ с расширением.bat, сохранённый вами.

Редактирование

Если захотите изменить документ — добавить в bat-файл команды, удалить некоторые из них, вписать другую программу для последующей работы с ней, — сделать это не сложно. Откройте документ посредством текстового редактора. Удобно это выполнить, нажав на bat-файл правой кнопкой, в открывшемся меню выбирайте «Изменить». Запустится «Блокнот» — там и можно редактировать команды, изменять содержание, вносит дополнения.

Description

echo is a fundamental command found in most operating systems. It is frequently used in scripts, batch files, and as part of individual commands; anywhere you may need to output text.

Most command shells, including bash, ksh and csh implement echo as a built-in command. The behavior of built-in echo commands is similar, but the options may be different; those commands are not documented here.

This document covers the stand-alone program, /bin/echo. Its options are slightly different than the built-in echo command that is included in your shell. If you are using the bash shell, you can determine which echo is the default, using the type command:

type echo
echo is a shell builtin

To specify that you want to run the stand-alone program instead of the shell built-in, use its complete path in the command, i.e., run it like this:

/bin/echo

This document describes the GNU/Linux stand-alone version of echo.

語法Syntax

參數Parameters

參數Parameter 描述Description
開啟或關閉命令回顯功能。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 command is particularly useful when echo is turned off. 若要顯示有數行的訊息,而不顯示任何命令,您可以 在 batch 程式的 命令之後包含數個命令。To display a message that is several lines long without displaying any commands, you can include several commands after the echo off command in your batch program.

  • 關閉 echo 之後,命令提示字元視窗中不會出現命令提示字元。After echo is turned off, the command prompt doesn’t appear in the Command Prompt window. 若要顯示命令提示字元,請 在上輸入 echo。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.

  • 若要顯示管道 () 或重新導向字元 ( 或在 使用 echo時) ,請使用插入 號 () 緊接在管道或重新導向字元之前。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:

注意

當 echo 關閉時,命令提示字元視窗中不會出現命令提示字元。When echo is turned off, the command prompt doesn’t appear in the Command Prompt window. 若要再次顯示命令提示字元,請 在上輸入 echo。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:

您可以使用 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):

Команда echo linux

Команда echo — это не системная утилита, у нее нет исполняемого файла. Она существует только внутри интерпретатора Bash. Синтаксис команды echo linux очень прост:

$ echo опции строка

Опций всего несколько, давайте рассмотрим их, чтобы вы могли лучше ориентироваться в работе утилиты:

  • -n — не выводить перевод строки;
  • -e — включить поддержку вывода Escape последовательностей;
  • -E — отключить интерпретацию Escape последовательностей.

Это все опции, если включена опция -e, то вы можете использовать такие Escape последовательности для вставки специальных символов:

  • /c — удалить перевод строки;
  • /t — горизонтальная табуляция;
  • /v — вертикальная табуляция;
  • /b — удалить предыдущий символ;
  • /n — перевод строки;
  • /r — символ возврата каретки в начало строки.

Пожалуй, это все, что нужно знать о команде echo, а теперь давайте рассмотрим как с ней работать.

语法Syntax

参数Parameters

参数Parameter 说明Description
打开或关闭命令回显功能。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 command is particularly useful when echo is turned off. 若要在不显示任何命令的情况下显示长达几行的消息,可以 在批处理程序中的 » echo off » 命令后包含多个命令。To display a message that is several lines long without displaying any commands, you can include several 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。To display the command prompt, type echo on.

  • 如果在批处理文件中使用, 回响 和 echo off 不会影响命令提示符下的设置。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. 若要防止在批处理文件中回显所有命令,请在文件开头包含 回响 off 命令。To prevent echoing all commands in a batch file, include the echo off command at the beginning of the file.

  • 若要 在使用 echo 时显示管道 () 或重定向字符 ( 或 ) ,请在echo 管道或重定向字符之前立即使用插入符号 () 。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。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):

Options

Options

These options may be specified before the string, and affect the behavior of echo.

-n Do not output a trailing newline.
-e Enable interpretation of backslash escape sequences (see below for a list of these).
-E Disable interpretation of backslash escape sequences. This is the default.

Options

If a long option is specified, you may not specify a string to be echoed. These options are for getting information about the program only.

—help Display a help message and exit.
—version Output version information and exit.

Escape sequences

If you specify the -e option, the following escape sequences are recognized in your string:

Sequence Interpreted as
\\ A literal backslash character («\«).
\a An alert (The BELL character).
\b Backspace.
\c Produce no further output after this.
\e The escape character; equivalent to pressing the escape key.
\f A form feed.
\n A newline.
\r A carriage return.
\t A horizontal tab.
\v A vertical tab.
\0NNN byte with octal value NNN (which can be 1 to 3 digits).
\xHH byte with hexadecimal value HH (which can be either 1 or 2 digits)

NOTE

each shell generally has its own implementation of echo, which may be slightly different than the version described here. Refer to your shell’s documentation for details about the options it supports.

Часть седьмая. Упаковка исполнительного файла

Здесь хочу отметить, что мало кто станет запускать ваш батник хотя бы потому, что он имеет немного подозрительный вид. Исправить это можно двумя способами:

Упаковка батников в SFX-архив

Второй вариант в рамках данной статьи чуток подробнее и рассмотрим.
— Для начала нам надо установить на ПК подходящий архиватор (для этих целей я рекомендую WinRAR, т.к. создание sfx-архивов в нём реализовано наиболее удобно и просто).
— Создаём нужный нам пакетный файл (батник).
— Кликаем правой кнопочкой по батнику, выбираем из контекстного меню WinRAR => Добавить в архив (дальше по вкладкам)
— Общие. Имя любое. Формат — RAR. Метод сжатия обычный. В параметрах архивации ставим галочку напротив Создать SFX-архив.
— Дополнительно. Жмём на кнопочку Параметры SFX… Вкладочка «Общие», выполнить после распаковки — вписываем имя архивируемого батника с расширением. Во вкладке «Режимы» в разделе «Режим вывода информации» ставим галочку напротив «Скрыть всё». На вкладочке «Текст и графика» можно, например, добавить симпатичную иконку вашему архиву вместо стандартной. Если вы не художник, то иконку можно вытащить из любой программы/игры при помощи стороннего софта, например Restorator.
— На этом всё. Остальные опции на ваше усмотрение. Жмём кнопочку ОК. В исходной папке с батником появится ещё и наш новый sfx-архив.
— Чтобы добавить солидность файлу, позволить ему прибавить в весе, можно в архив «напихать» ещё что-нибудь, это может быть что угодно, т.к. цель — только увеличение размера.
— В архиве может быть сколько угодно батников, при создании архива мы указываем, что выполнять нужно первый (прописываем его имя с расширением), чтобы после этого выполнился следующий, в конце (либо в нужном нам месте) пишем

call sled.bat

Т.е. когда дело дойдёт до этой команды, система переключится на исполнение файла с названием sled.bat, а затем вернётся к исходному.
Если же надо, чтобы работа первого батника не прерывалась, то используем другую команду

start sled.bat
Добавить комментарий

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