Echo from file linux

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.

Читайте также:  Undertale для mac os

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.

Источник

Команда 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 в двойные или одинарные кавычки.
  • При использовании одинарных кавычек » буквальное значение каждого символа, заключенного в кавычки, будет сохранено. Переменные и команды расширяться не будут.
Читайте также:  Можно ли удалять папку windows mail

echo Примеры

В следующих примерах показано, как использовать команду echo:

Вывести строку текста на стандартный вывод.

Отобразите строку текста, содержащую двойные кавычки.

Чтобы напечатать двойную кавычку, заключите ее в одинарные кавычки или экранируйте символ обратной косой черты.

Отобразите строку текста, содержащую одинарную кавычку.

Чтобы напечатать одинарную кавычку, заключите ее в двойные кавычки или используйте кавычки ANSI-C .

Вывести сообщение, содержащее специальные символы.

Используйте параметр -e чтобы включить интерпретацию escape-символов.

Символы соответствия шаблону.

Команда echo может использоваться с символами сопоставления с образцом, такими как подстановочные знаки. Например, приведенная ниже команда вернет имена всех файлов .php в текущем каталоге.

Перенаправить в файл

Вместо отображения вывода на экране вы можете перенаправить его в файл с помощью операторов > , >> .

Если файл file.txt не существует, команда создаст его. При использовании > файл будет перезаписан, а символ >> добавит вывод в файл .

Используйте команду cat для просмотра содержимого файла:

Отображение переменных

echo также может отображать переменные. В следующем примере мы напечатаем имя текущего вошедшего в систему пользователя:

$USER — это переменная оболочки, в которой хранится ваше имя пользователя.

Отображение вывода команды

Используйте выражение $(command) чтобы включить вывод команды в аргумент echo . Следующая команда отобразит текущую дату :

Отображение в цвете

Используйте escape-последовательности ANSI, чтобы изменить цвета переднего плана и фона или установить свойства текста, такие как подчеркивание и полужирный шрифт.

Выводы

К настоящему времени вы должны хорошо понимать, как работает команда echo .

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

16 Echo Command Examples in Linux

Echo command in Linux is one of the widely used command in day-to-day operations task. The echo command is a built-in command-line tool that prints the text or string to the standard output or redirect output to a file. The command is usually used in a bash shell or other shells to print the output from a command. Echo command is also used frequently in bash shell scripts.

Syntax of echo command

$ echo [option] [string]

In this guide, we will explain Linux echo command with 16 practical examples.

1) Display a simple message on the terminal

To print a simple text message on the terminal with echo command , run the command:

2) Print out the value of a variable with echo command

Let’s assume that you have initialized a variable x and assigned it a value of 100 as shown

You can echo its value by prefixing the variable name with a dollar sign as shown

3) Print a line of text comprising of double quotes

To print a line of text with double quotes with echo command, simply enclose the phrase in double-quotes between single quotes.

4) Display a line of text consisting of a single quote

If you wish to print a line with a word containing a single quote, enclose the word inside double quotation marks as shown:

Читайте также:  Samsung grand prime windows

5) Redirect echo command output to a file

To redirect echo command output to a file instead of printing it on the screen use the greater than( > ) and double greater than ( >> ) operators.

When you use the greater than( > ) operator, the file will be overwritten. If the file does not exist, it will be created.

The double greater than operator ( >> ) appends text to a file. For example, to add an entry to the /etc/hosts files use the syntax shown

6) Use echo command to match identical files

You can use echo command with a wildcard character to return identical files i.e files that bear the same file extension. For example, to print out all text files with the .txt extension , run the command.

7) List all files and folders in the current directory

The echo command can act as the ls command and list all the files and folders in your current directory using the wildcard as shown:

8) Create new lines using the echo command

Using the backslash interpreter -e , you can manipulate how the line appears on the output. For example, to print a new line, use the ‘ \n ‘ escape character option as shown below:

9) Create tab spaces between words in a sentence

Apart from creating a new line, you can increase the spacing between words in a sentence using the ‘\t ‘ or TAB option as shown.

10) Combine new line and tab spacing options in echo command

You can combine the ‘\n’ and ‘\t’ options at the same time as shown:

11) Create vertical tab spaces in echo command output

The \v option enables you to create vertical tab spaces as shown:

12) Combine new line and vertical tab spaces in echo command

Additionally, you can experiment and combine the ‘\n’ and ‘\v ‘ options as shown.

13) Use the carriage return option

The \r option omits the preceding text. For example, the output of the command below omits the first 2 words.

14) Truncate echo command output of text

To suppress any further output and proceed without going to the next line use the ‘\c’ option as shown:

15) Remove all spaces from the text string with echo command

Use ‘ \b’ option along with -e option in echo command to remove all the spaces from the text string, example is shown below:

16) Echo command usage in bash shell script

As we have already stated that echo command is frequently used in bash shell scripts. Example of echo command usage in shell script are listed below:

Output of above script when it is executed:

And that’s it. Thank you for taking your time in this guide. Hopefully, you are now better informed.

Also Read : 14 Grep Command Examples in Linux

Источник

Оцените статью