- Linux Echo Command and Usage Examples
- Man Echo
- Syntax
- Display Text
- Print Variables
- Remove Spaces While Printing
- Bash Echo New Line
- Vertical Tab
- Carriage Return
- Backspace
- Omit New Line
- Alert
- Print All Files and Folders
- Print specific Extension Files
- Write Into File
- Create Empty File
- Add To The File
- Команда Echo в Linux с примерами
- эхо-команда
- echo Примеры
- Выводы
- echo command in Linux with Examples
- 15 Practical Examples of ‘echo’ command in Linux
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Linux Echo Command and Usage Examples
Echo is popular command comes with all of the Linux distributions. Echo is provided by bash and C shells. Echo simple outputs are given values to the console or terminal.
Man Echo
To get more detailed help and echo official documentation use following command
Man Echo
Syntax
Echo command provides two types of syntax like below.
Display Text
Simple and most common usage of echo command is just printing specified text to the standard output like below.
Display Text
Print Variables
Another popular usage form is printing shell variables like below.
Print Variables
Remove Spaces While Printing
There is -e option which will remove all spaces by using backspaces defined with \b while printing text
Remove Spaces While Printing
Bash Echo New Line
Another useful usage is adding \n control character which will print a new line.
While printing some text to the standard output tabs can be placed into this text by using \t
Tab
Vertical Tab
Vertical tab will provide new line and align the output text like below.
Vertical Tab
Carriage Return
A carriage return will delete previous part of the text and only print after last carriage return with \r
Carriage Return
Backspace
Backspace control character will delete a single character to the backward with \b in the text.
Backspace
Omit New Line
Normally after printing text to the standard output new line is provided to make things more clear. But this new line can be prevented with option -n
Omit New Line
Alert
Alert can provided to the shell subsystem with \a . This is very useful to make shell scripts and application more interactive
Alert
This option will not affect the output of the text.
Print All Files and Folders
Echo command can work with bash features easily. To easily and simply print all files and folders of the current directory following command can be used.
Print specific Extension Files
While printing files and folders specific extensions can be used to filter output. For example, we want to print to the standard output only c source files with the extension .c
Print specific Extension Files
Write Into File
Without opening any text editor some text can be written to a file. The file must not preexist. If file is all ready exist all content is deleted and given text is written to the text file.
Create Empty File
An empty file can be created by providing an empty string definition and redirecting this to a file.
Create Empty File
Add To The File
The last example of the echo command is adding more text to the existing file. Adding operation will no delete existing text in the file.
Источник
Команда Echo в Linux с примерами
Команда echo — одна из самых основных и часто используемых команд в Linux. Аргументы, переданные в echo выводятся на стандартный вывод.
echo обычно используется в сценариях оболочки для отображения сообщения или вывода результатов других команд.
эхо-команда
echo — это оболочка, встроенная в Bash и большинство других популярных оболочек, таких как Zsh и Ksh. Его поведение немного отличается от оболочки к оболочке.
Существует также отдельная утилита /usr/bin/echo , но обычно встроенная версия оболочки имеет приоритет. Мы рассмотрим встроенную в Bash версию echo .
Синтаксис команды echo следующий:
- Когда используется опция -n , завершающий символ новой строки подавляется.
- Если задана опция -e будут интерпретироваться следующие символы, экранированные обратной косой чертой:
- \ — отображает обратную косую черту.
- a — Предупреждение (BEL)
- b — отображает символ возврата.
- c — подавить любой дальнейший вывод
- e — отображает escape-символ.
- f — отображает символ перевода страницы.
- n — отображает новую строку.
- r — отображает возврат каретки.
- t — отображает горизонтальную вкладку.
- v — отображает вертикальную вкладку.
- Параметр -E отключает интерпретацию escape-символов. Это значение по умолчанию.
При использовании команды echo следует учитывать несколько моментов.
- Оболочка заменит все переменные, сопоставление подстановочных знаков и специальные символы перед передачей аргументов команде echo .
- Хотя это и не обязательно, рекомендуется заключать аргументы, передаваемые в echo в двойные или одинарные кавычки.
- При использовании одинарных кавычек » буквальное значение каждого символа, заключенного в кавычки, будет сохранено. Переменные и команды расширяться не будут.
echo Примеры
В следующих примерах показано, как использовать команду echo:
Вывести строку текста на стандартный вывод.
Отобразите строку текста, содержащую двойные кавычки.
Чтобы напечатать двойную кавычку, заключите ее в одинарные кавычки или экранируйте символ обратной косой черты.
Отобразите строку текста, содержащую одинарную кавычку.
Чтобы напечатать одинарную кавычку, заключите ее в двойные кавычки или используйте кавычки ANSI-C .
Вывести сообщение, содержащее специальные символы.
Используйте параметр -e чтобы включить интерпретацию escape-символов.
Символы соответствия шаблону.
Команда echo может использоваться с символами сопоставления с образцом, такими как подстановочные знаки. Например, приведенная ниже команда вернет имена всех файлов .php в текущем каталоге.
Перенаправить в файл
Вместо отображения вывода на экране вы можете перенаправить его в файл с помощью операторов > , >> .
Если файл file.txt не существует, команда создаст его. При использовании > файл будет перезаписан, а символ >> добавит вывод в файл .
Используйте команду cat для просмотра содержимого файла:
Отображение переменных
echo также может отображать переменные. В следующем примере мы напечатаем имя текущего вошедшего в систему пользователя:
$USER — это переменная оболочки, в которой хранится ваше имя пользователя.
Отображение вывода команды
Используйте выражение $(command) чтобы включить вывод команды в аргумент echo . Следующая команда отобразит текущую дату :
Отображение в цвете
Используйте escape-последовательности ANSI, чтобы изменить цвета переднего плана и фона или установить свойства текста, такие как подчеркивание и полужирный шрифт.
Выводы
К настоящему времени вы должны хорошо понимать, как работает команда echo .
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Источник
echo command in Linux with Examples
echo command in linux is used to display line of text/string that are passed as an argument . This is a built in command that is mostly used in shell scripts and batch files to output status text to the screen or a file.
Syntax :
Displaying a text/string :
Syntax :
Example :
Options of echo command
NOTE :- -e here enables the interpretation of backslash escapes
1. \b : it removes all the spaces in between the text
Example :
2. \c : suppress trailing new line with backspace interpretor ‘-e‘ to continue without emitting new line.
Example :
In above example, text after \c is not printed and omitted trailing new line.
3. \n : this option creates new line from where it is used.
Example :
4. \t : this option is used to create horizontal tab spaces.
Example :
5. \r : carriage return with backspace interpretor ‘-e‘ to have specified carriage return in output.
Example :
In the above example, text before \r is not printed.
6. \v : this option is used to create vertical tab spaces.
Example :
7. \a : alert return with backspace interpretor ‘-e‘ to have sound alert.
Example :
This command when executed, it will produce an alert sound or Bel .
8. echo * : this command will print all files/folders, similar to ls command .
Example :
9. -n : this option is used to omit echoing trailing newline .
Источник
15 Practical Examples of ‘echo’ command in Linux
The echo command is one of the most commonly and widely used built-in commands for Linux bash and C shells, that typically used in a scripting language and batch files to display a line of text/string on standard output or a file.
echo command examples
The syntax for the echo command is:
1. Input a line of text and display it on standard output
Outputs the following text:
2. Declare a variable and echo its value. For example, Declare a variable of x and assign its value=10.
Note: The ‘-e‘ option in Linux acts as an interpretation of escaped characters that are backslashed.
3. Using option ‘\b‘ – backspace with backslash interpretor ‘-e‘ which removes all the spaces in between.
4. Using option ‘\n‘ – New line with backspace interpretor ‘-e‘ treats new line from where it is used.
5. Using option ‘\t‘ – horizontal tab with backspace interpretor ‘-e‘ to have horizontal tab spaces.
6. How about using option new Line ‘\n‘ and horizontal tab ‘\t‘ simultaneously.
7. Using option ‘\v‘ – vertical tab with backspace interpretor ‘-e‘ to have vertical tab spaces.
8. How about using option new Line ‘\n‘ and vertical tab ‘\v‘ simultaneously.
Note: We can double the vertical tab, horizontal tab, and new line spacing using the option two times or as many times as required.
9. Using option ‘\r‘ – carriage return with backspace interpretor ‘-e‘ to have specified carriage return in output.
10. Using option ‘\c‘ – suppress trailing new line with backspace interpretor ‘-e‘ to continue without emitting new line.
11. Omit echoing trailing new line using the option ‘-n‘.
12. Using option ‘\a‘ – alert return with backspace interpretor ‘-e‘ to have the sound alert.
Note: Make sure to check the Volume key, before firing.
13. Print all the files/folders using echo command (ls command alternative).
14. Print files of a specific kind. For example, let’s assume you want to print all ‘.jpeg‘ files, use the following command.
15. The echo can be used with a redirect operator to output to a file and not standard output.
echo Options
Options | Description |
-n | do not print the trailing newline. |
-e | enable interpretation of backslash escapes. |
\b | backspace |
\\ | backslash |
\n | new line |
\r | carriage return |
\t | horizontal tab |
\v | vertical tab |
That’s all for now and don’t forget to provide us with your valuable feedback in the comments below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник