Linux echo one line

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.

Читайте также:  Windows 10 боковая панель слева

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 — это очень простая и в то же время часто используемая встроенная команда оболочки Bash. Она имеет только одно назначение — выводить строку текста в терминал, но применяется очень часто в различных скриптах, программах, и даже для редактирования конфигурационных файлов.

В этой статье мы рассмотрим что представляет из себя команда echo linux, как ее можно использовать и в каких ситуациях. Но сначала рассмотрим синтаксис самой команды.

Команда echo linux

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

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

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

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

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

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

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

Примеры работы echo

Давайте рассмотрим как пользоваться echo. Сначала просто выведем строку на экран:

echo Linux Open Source Software Technologies

Также можно вывести значение переменной. Сначала объявим переменную:

Затем выведем ее значение:

echo Наш сайт $VAR

Как уже говорилось, с помощью опции -e можно включить интерпретацию специальных последовательностей. Последовательность \b позволяет удалить предыдущий символ. Например, удалим все пробелы из строки:

echo -e «Linux \bopen \bsource \bsoftware \btechnologies»

Последовательность \n переводит курсор на новую строку:

Читайте также:  Утилита telnet для windows

echo -e «Linux \nopen \nsource \nsoftware \ntechnologies»

С помощью \t вы можете добавить горизонтальные табуляции:

echo -e «Linux \topen \tsource \tsoftware \ttechnologies»

Можно совместить переводы строки и табуляции:

echo -e «Linux \tnopen \tnsource \tnsoftware \tntechnologies»

Точно так же можно применить вертикальную табуляцию:

echo -e «Linux \vopen \vsource \vsoftware \vtechnologies»

С помощью последовательности \r можно удалить все символы до начала строки:

echo -e «Linux \ropen source software technologies»

Последовательность -c позволяет убрать перевод на новую строку в конце сообщения:

echo -e «Linux open source software technologies\c»

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

  • \033[30m — чёрный;
  • \033[31m — красный;
  • \033[32m — зелёный;
  • \033[33m — желтый;
  • \033[34m — синий;
  • \033[35m — фиолетовый;
  • \033[36m — голубой;
  • \033[37m — серый.

И такие цвета фона:

  • \033[40m — чёрный;
  • \033[41m — красный;
  • \033[42m — зелёный;
  • \033[43m — желтый;
  • \033[44m — синий;
  • \033[45m — фиолетовый;
  • \033[46m — голубой;
  • \033[47m — серый;
  • \033[0m — сбросить все до значений по умолчанию.

Например. раскрасим нашу надпись в разные цвета:

echo -e «\033[35mLinux \033[34mopen \033[32msource \033[33msoftware \033[31mtechnologies\033[0m»

С основными параметрами команды echo разобрались, теперь рассмотрим еще некоторые специальные символы bash. Вы можете вывести содержимое текущей папки просто подставив символ *:

Также можно вывести файлы определенного расширения:

Я уже говорил, что echo можно использовать для редактирования конфигурационных файлов. Вы можете использовать запись echo в файл linux, если он пуст:

echo 1 > /proc/sys/net/ipv4/ip_forward

Если файл не пуст, и вам необходимо добавить свою строчку в конец файла используйте символ перенаправления вывода >>:

echo «UUID=09ec0871-2f55-4dd5-aeb2-cacc4a67907c /var/tmp btrfs subvol=@/var/tmp 0 0» >> /etc/fstab

Если строка содержит какие-либо специальные символы или может быть понята интерпретатором неоднозначно, следует заключить ее в кавычки.

Выводы

В этой статье была рассмотрена команда echo linux. Несмотря на свою простоту, она может применяться для решения различных задач и незаменима при написании простых скриптов. Надеюсь, эта информация была вам полезной.

Источник

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.

Читайте также:  Eye tracker windows 10

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:

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

Источник

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