Set echo on linux

How to use Linux echo command

Linux distributions allow you to set up and control the system yourself. In this context, the bash echo command belongs to one of the most used commands. It is used in bash scripts and batch files to output a status text in a file or on your screen. We explain how the Linux echo command works and how, for example, colors for font and background can be determined with it.

What is an echo command and how does it work?

The Linux echo command repeats what you have told it to repeat. The function is extremely simple, but required to do just that. For example, without echo, you would not get visible output from shell scripts. Shell is the user interface where you can enter different commands, such as the Linux tail command, the Linux head command, the Linux cat command or else the Linux echo command.

How exactly does the Linux echo command work and what is its syntax? Here is an example of the general syntax of the command:

The basic operation of echo is the same in all programming languages. You make an input — which in most cases is in the form of a string — and this is received and output again unchanged.

The user interface or command line interpreter shell is also called bash shell. Bash is the standard shell in Linux distributions and the text window in which you enter your commands. The program echo is an elementary part of Ubuntu and preinstalled on every system.

How to output text and information in Linux with echo commands

In our first example, we want to output a text and the contents of variables in bash and terminal, respectively. To write the text “This is an example”, enter the following code into the terminal:

$ echo This is an example This is an example 

To avoid errors as much as possible, we recommend that you enclose the text in quotation marks:

$ echo "This is an example" This is an example 

In the next step we want to output a variable. Here it is enough to enter the name of the variable, such as PWD (for Print Working Directory or your working directory). The command would then look like this:

$ echo $PWD /Users/Name/Desktop

Then there is also the possibility to combine the output of variables with text, as in this example:

$ echo "You are in the directory: $PWD" You are in the directory: /Users/Name/Desktop

For the output of information there is not only the bash echo command, but also printf and tput. tput is the more complex tool and can also be used to reset information. With printf and echo, however, only information can be output.

Читайте также:  Linux вывести содержимое папки

What are the control characters for echo?

Once you have understood the basic principle of the Linux echo command, the next step is to learn which control characters you can use in combination with the command. Control characters are characters that are not directly visible on the screen, but determine things like the beginning of text, the end of text, or line breaks.

Attention! Echo understands control characters only if you set the -e option. In the following example, “\n” is therefore mapped as text only. (The control character “\n” signals newline or a text wrap).

However, if you add -e, as in the following example, a text break happens in your text:

Источник

Команда 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

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

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

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

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

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

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. Для доступны такие цвета текста:

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

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

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

Читайте также:  Linux mint перестал обновляться

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

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

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Echo Command in Linux

The Linux operating system is widely used to host applications on servers, and system administrators use various shell scripts, batch files, and variables to automate tasks. The variables and script output may not be understandable to the users. In such cases, you can use the echo command to display string or text on standard output.

In this tutorial, you will learn about the echo command in Linux using practical examples.

Prerequisites

  • Linux operating system access.
  • Familiarity with Linux command-line interface.
  • Willingness to learn new Linux commands with examples.

Linux Echo Command

Echo is one of the most commonly used Linux commands that is used to print the specified argument on the screen and print variable values. The echo command in Linux is a shell built-in command, which is available by default.

The most common use of the echo command is to output the text or strings that you pass as an argument to this command. The echo command arguments include static text, shell variables, environment variables, file names, and directories. The echo command works on all major Linux distributions, including Red Hat, Debian, Ubuntu, and Fedora.

Echo Command Syntax

The basic syntax of the echo command is:

echo [option] [string] [variable]

The most commonly used syntax of this command is to enter the string or a line of text after the echo command:

The standard output of the above command will be the specified string:

Echo Command Options

The echo command options enable you to modify the standard output per your requirements.

Option Description
-n Display the output without a newline after it. This option suppresses the trailing newline.
-E Disable the escape characters’ interpretation. This is the default option.
-e Enable the following escape characters interpretation:
\\ Display backslash-escaped characters.
\a Display the output with a sound alert.
\b Create a backspace character, which is equivalent to using the backspace key.
\c Ignore any output after the escape character.
\e Create an escape character, which is equivalent to using the Esc key.
\f Create a form feed character, which makes the printer automatically go to the beginning of the next page.
\n Add a new line in the output.
\r Perform a carriage return.
\v Create vertical tab spaces.
\t Create horizontal tab spaces.
\NNN Octal byte value of NNN.
\xHH Hexadecimal byte value of HH.
Читайте также:  Oracle sql developer for linux

Echo Command Examples

The echo command in Linux provides various options that you can use to modify or format your output as per your requirements. The following echo examples describe some of the common use cases of this command:

Display Text

To display a simple line of text on the standard Linux output without any special characters or options, type:

Display line of text

For displaying a double quotation mark for a particular word, then use either a single quote for the entire string or use a backslash character for escape:

echo ‘Hello, “World!”’ echo “Hello \”World\””

 display a double quotation mark

For displaying a single quote mark or apostrophe, put the entire string in the double quotation marks:

echo “I’ll go to the office tomorrow.”

display a single quote mark or apostrophe

Use Escape Character with Echo

Use the -e option with the echo command to use escape characters. These special characters help you customize the echo command output.

For example, the \c escape character shortens the output string by not printing the output followed by the escape character. To avoid printing How are you in the following command output, use the echo -e option with /c escape character:

echo -e ‘Hello, World! \c How are you.’

option -e - using \c escape character

Use the \n escape character to move the output to a new line:

echo -e ‘Hello, \nWorld! \nHow \nare \nyou.’

option -e - using \n escape character

To add a horizontal tab before a word, use the \t escape character:

echo -e ‘Hello, \tWorld! \tHow \tare \tyou.’

option -e - using \t escape character

To add a vertical tab before a word, use the \v escape character:

echo -e ‘Hello, \vWorld! \vHow \vare \vyou.’

option -e - using \v escape character

To change the color of the text, you can use the ANSI escape sequence:

echo -e ‘\033[1;37mHello’ echo -e ‘\033[0;30mWorld!’ echo -e ‘\033[0;31mHow’ echo -e ‘\033[0;32mare’ echo -e ‘\033[0;33myou.’

using echo change the color of the text

You can also use echo -e to use multiple escape characters, such as /n for a new line and /t for a horizontal tab in a single command:

echo -e “Life is short. /n/t- A wise man.”

option -e - using multiple escape characters

You can also insert a special character after the new line.

For displaying environment variable and shell variable values as the echo command output, use the following echo command:

print the variable value of $PWD

Using the echo command you can print the result of other commands. You must specify the command in $(command) format, for example, the $(ls) command will display the existing content of the current directory.

To display the output of the other commands along with the specified text string, you can use the following command:

echo -e “File system information of the users.txt file: \n $(stat users.txt)”

display other commands outputs with a string

Empty File

You may use the echo command to empty file (clear the file contents) in Linux. You can pass an empty string or redirect to the file as follows:

echo "" > error.log or echo > error.log

Conclusion

In this tutorial, we learned how to use the Linux echo command to print a specific string on the standard Linux output. This command is also used to print environment variable values and command output. The echo command also supports various escape characters that you can use to format the output as per your requirements.

If this resource helped you, let us know your care by a Thanks Tweet. Tweet a thanks

Источник

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