Linux echo command and scripting with nodejs
So this will be a quick post on using the Linux echo command and node.js when it comes to creating shell scripts with javaScript rather than the usual Bourne Shell. The echo command just simply prints something to the standard output, in some cases now and then I find myself using it. For example just simply piping in some kind of simple test input to a CLI tools standard input would be one reason why I would go about using the echo command. The test output that echo creates can be used as a place holder of sorts for input from something else that would prove to be a real use case scenario.
The echo command can have many real would use cases also though, for example when writing a bash script I might want to print some result in string form to the standard output when the script is called, one way to do so would be to use the echo command and pass that string value as the first argument. When doing so there are a number of options that can be used to set of there should be a line break at the end or not, or if some special characters should be used or not to create the final output.
So in this post I will be going over some basic example of the Linux echo command, and also go over some of the advanced options that often prove to be useful when using it.
1 — Some basics of the Linux echo command by itself
So before getting into some javaScript it might be best to just start out playing around with some commands in the terminal with Linux echo by itself. I would say that the echo command is one of those basic commands in Linux that everyone that uses Linux, or a posix environment in general should be aware of. The command comes up a lot, so it pays to be familiar with many of the options ans and basic use case examples.
1.1 — basic Linux Echo
So if I type echo in the command line and then give a string the echo command will just echo that to the standard output of the console.
That is it that is the basic idea of what echo is for.
1.2 — Sometimes I might need to escape things
In some situations I might need to use the escape option so that things will render the way that they should in the console, or in any destination in which the result will ultimately end up. For example say I want to put some new lines in a string with the backslash n syntax.
So this is the only option I often find myself using now and then so I thought I would have a brief section here on this.
1.3 — make it so echo will not add a line feed at the end
By default the echo command will add a line feed character at the end of the output. Most of the time I will want to have a line feed at the end of the output that echo spits out to the console, however in some cases I might want that to not happen actually. For these kinds of situations there is the -n option of the echo command that I can use to make it so the echo command will not append that final line feed charterer.
1.4 — Piping example
One major use case example of using the echo command is to just create some test standard output when it comes to playing around with a new command to learn what it can do when it comes to feeding it something with the standard input. For example take the base32 command, this command can take some input from the standard input and spit out a base32 form of that input. However in order to test it out I need to have some input to pipe into it and one way to do so would be to use the echo command.
There are other options of course, for example if I had a text file that I wanted to pipe into it I could use the cat command to do so. However when it comes to doing something like this I might also want to write the results of it to a file also, and with that said I think I should move on into another Linux echo example that make used of redirection.
1.5 — Redirection example
Linux Bash Redirection is another feature of bash that I think I should cover here while I am at it. With that said the Linux echo command combined with redirection can be used as a way to create text files from the command line. The echo command can be used as a way to generate some standard output, and then redirection can in turn be used to create a file with that standard output.
2 — The Linux Echo command nodejs examples
So when working out a nodejs script that needs to split something out to the standard output, I could use the spawn child process to use the echo command. However there are some other ways to do so that are more piratical when working in a javaScript environment. Namely there is the console log method that will also echo something to the standard output and append a line beak just line that of the Linux echo command. In addition there is also the stdout property of the process global that is an instance of a writable stream. Still I do like nodejs, and javaScript so I have to have a section on using that here.
2.1 — Using spawn in child process to call the Linux Echo command
So first off a basic node script where I am using the child process module as a way to call the Linux Echo Command. However I will also be showing the two general ways to go about spitting something out into the standard output when it comes to nodejs scripts also here which are what should be used in a nodejs script.
2.2 — Using Linux Echo to pipe in some data to the standard input of a nodejs script
One of the typical use case examples when making a CLI tool, or Shell Script with nodejs is to use echo to pipe some kind of test input to the standard input of a script. In my nodejs script I can just use the stdin property of the process global to attach an event handler that will do something on a per chunk bases with that input.
Fo a quick example here is a script that just converts the data that is piped in to hex.
With many of my real projects so far what is actually being piped in might be the full body of text of a blog post that is actually being piped in via another script. Also the script that I am piping into does something more than just convert that text to hex, but this is the basic idea never the less.
2.3 — The deal with a backslash
One of the options of the Linux echo command is the -e option that can be used to enable the processing of backslashes as a way to inject certain characters.
3 — Conclusion
Well that is it for now when it comes to the Linux echo command, but there really is only so much to write about when it comes to this topic. The echo command is just one way to go about creating some standard output from the string value that is given to it as an argument. So as the name suggests it just echos what is given to it as an argument to the standard output of the console.
Play with “echo” in Bash
“Echo” is like print in any programming languages. But there’s quite a number of differences in Bash. Let’s dive in to see
Automation with Love
- Echo syntax
Written by Donald Le
Automation with Love
A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.
Использование команды echo в Linux
Как известно, большинство действий в операционной системе Linux осуществляются через консоль. Пользователи задействуют специальные команды, отвечающие за выполнение определенных процессов, а заранее указанные опции позволяют собственными руками управлять дополнительными возможностями тех самых утилит. Одной из таких команд является echo, и сегодня мы хотим более детально рассказать об этой утилите, приведя несколько примеров ее использования.
Используем команду echo в Linux
Рассматриваемая сегодня команда echo имеет примитивный вид и узкопрофильное предназначение — выводить текст на экран. Однако это не мешает ей часто использоваться в различных скриптах и для других целей. Далее мы предлагаем вкратце ознакомиться с синтаксисом данной утилиты и разобрать самые популярные и простые примеры ее ввода в стандартной консоли.
Синтаксис echo
Практически каждая команда помимо основной своей функции может выполнять и другие действия с учетом указанных аргументов. echo не стала исключением в этом плане, однако из-за простоты самой команды расширенных опций существует не так уж и много. Давайте подробнее рассмотрим каждую из них, но сначала обратите внимание на стандартный вид строки: echo + опции + строка .
Опции | Описание |
---|---|
-n | Не будет выводить перенос строки |
-e | Отвечает за включение Escape-последовательностей |
-E | Отключает интерпретацию Escape-последовательностей |
Отметим также, что Escape-последовательности — универсальные опции, представленные в виде символов. Каждая из них имеет определенное значение, и если вы включите интерпретацию при использовании команды echo, то можете задействовать такие аргументы:
Опции | Описание |
---|---|
/c | Отвечает за удаление перевода строки |
/t | Выводит горизонтальную табуляцию |
/v | Создает вертикальную табуляцию |
/b | Удаляет предыдущий символ в строке |
/n | Включает перенос строки на новую |
/r | Возвращает каретку в начало строки |
Еще раз уточним, что приведенные выше опции доступны к вводу только в тех ситуациях, когда вы изначально прописали аргумент -e в команде. Если есть необходимость, каждый этот символ можно проставить после любого из слов строки ввода, что мы покажем в следующих инструкциях.
Вывод простых строк
Как уже было сказано ранее, основное предназначение команды echo — вывод на экран строк. Именно об этом мы и хотим поговорить далее, рассмотрев несколько простых действий, которые помогут понять, как именно работают все основные опции утилиты.
- Запустите консоль удобным для вас образом, например через меню приложений или путем нажатия на горячую клавишу Ctrl + Alt + T. Здесь введите echo + любое слово или словосочетание, чтобы проверить стандартное действие команды. Активируется она нажатием на клавишу Enter.
- Как видите, в новой строке отобразились только что введенные слова в точно таком же формате.
- Если перед каждым словом вы добавите опцию \b , предыдущий символ будет стерт, а это значит, что результат выведется без пробелов, при условии, что мы имеем изначальный вид echo -e «Lumpics \bSite \bLinux» .
- Мы проставили указанную опцию во всех словах, поэтому результат получился соответствующий.
Теперь вы знаете, что команда echo способна выводить заданные строки в любом виде, который можно реализовать путем указания соответствующих опций. Давайте перейдем к другим параметрам, чтобы вы понимали, какие из них стоит комбинировать в правильном формате.
Вывод значений переменной
Практически в каждом скрипте используются определенные переменные, в которые заранее устанавливается значение. Если речь идет об утилите echo, то она способна выводить те самые значения. Мы рассмотрим этот пример в одной терминальной сессии без предварительного создания самого скрипта. Это обозначает, что при перезапуске консоли значения будут стерты.
- Для начала создадим пробную переменную введя export I=Lumpics , где I — имя переменной, а Lumpics — ее значение.
- Используйте echo $I , чтобы вывести в следующей строке значение обозначенной переменной.
- Как видите, все отобразилось корректно.
- Создадим еще одну переменную через export L=Linux .
- Введем пробную команду echo $I Site $L .
- Теперь вы знаете, что echo справляется с выводом двух и более переменных в формате одной строки.
В большинстве случаев подобный вывод переменных используется только при написании скриптов, однако подобная функция может пригодится, если планируется производить ряд одинаковых, зависимых от одного значения, действий в пределах одной терминальной сессии.
Присвоение цветов строке
Если вы активно используете консоль, то знаете, что каждое слово здесь может принять любой доступный цвет, а не только белый или черный (в зависимости от темы «Терминала»). echo тоже позволяет раскрашивать строки, а отвечают за это такие аргументы:
Аргумент | Цвет |
---|---|
\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[33mLumpics \033[46mSite \033[41mLinux» .
Приведенный выше пример окрасил фон строки «Lumpics» в оранжевый цвет, а к «Site» и «Linux» дополнительно были активированы фоны разных цветов. Вы это видите на приведенном ниже скриншоте действия введенной команды.
Специальные символы Bash
Команда echo функционирует только в среде Bash, соответственно, она должна поддерживать стандартные опции этого окружения. В большинстве случаев они отвечают за сортировку файлов и вывод объектов текущего расположения.
- Введите в «Терминале» echo * , чтобы показать содержимое текущей папки.
- Следующей строкой появится перечень абсолютно всех входящих директорий и элементов. Это будет стандартная строка без оформления. Однако теперь вы уже знаете, что ее можно видоизменить на основании примеров выше.
- Укажите echo *.txt , если хотите отобразить только элементы обозначенного формата. Замените .txt на другой необходимый вариант.
- В конце отметим, что echo выступает и для редактирования конфигурационных файлов, что осуществляется так: echo 1 > /proc/sys/net/ipv4/ip_forward . 1 — строка для внесения, а /proc/sys/net/ipv4/ip_forward — путь к нужному объекту.
В рамках сегодняшнего материала мы разобрались с использованием echo в операционной системе Linux. Если вас заинтересовала тема взаимодействия с популярными командами, дополнительно рекомендуем изучить статью по этой теме на нашем сайте, перейдя по указанным ниже ссылкам.
Echo linux команда что делает
A Practical Guide To Linux Echo Command
11 minute read Updated: February 9, 2023
Linux is one of the most popular operating systems. It has a powerful command-line interface that allows various commands to be passed as instructions to be executed by the computer. The echo command is one of the most commonly used Linux commands.
This tutorial will introduce you to the Linux echo command, go over its options and their usage, and show you how you can use it.
What Is the echo Command?
echo is a built-in Linux command that is used to display the text passed in as an argument. It is one of the basic Linux commands used in shell scripting and Bash files to display output status text at the command line.
Just like the Python print() function that is used to display texts on the screen, echo is used in Linux, Bash, and C shells for the same purpose. It has a simple syntax with various options:
The argument is the text or the message you want to display on the terminal, while the option is used to modify the behavior of the text passed.
For example, to suppress the newline character and display the message “Hello, world!” on a single line, you’ll run the following command:
Understanding the echo Command Options and Their Uses
The echo command has a few options that are used to format the string output to the screen. This section will go over some of these options.
Use n to Omit Trailing Newlines
echo prints your output on a new line by default. You can omit trailing newlines by using the n option.
Here’s an example:
You can also print multiple lines of text without adding new lines after each line; use the n option with the echo command.
Use -e to Add Various Escape Characters
-e character allows you to use the various escape characters to format the output of your argument in different ways. The option allows echo to interpret these characters.
The following escape characters are used with echo :
Use \a for Alert
\a character allows you to sound an alert like a beep with an echo when the output is displayed.
Here’s an example:
Use \b for Backspace
The \b character is a backspace character. It is used to erase the previous character in the output string. When the \b character is encountered in the output string, the terminal emulator will erase the previous character and move the cursor one position to the left.
Consider the following examples:
- Print a string with a backspace character
In the example above, s is erased, and the remaining text is in the output. 2. Print a string with a backspace character at the end
In the example above, the last letter is erased. 3. Print a string with multiple backspace characters.
Use \c to Trim Output
The ‘c’ character in the echo command suppresses the trailing newline that is automatically added to the end of the output. This is useful when printing a string of text that another command or string of text must immediately follow without a line break in between.
Here’s an example:
Here, “good” is truncated, and everything before the \c is printed out.
You can also print a string with \c and a custom delimiter:
Use \f for Form Feed
\f : This means the form feed character, and it lets the printer advance to the next page.
You can use the form feed character \f with the echo command to insert a page break in a text file. For example, the following command will insert a page break in a text file named “newfile.txt”:
The second example of using the form feed character \f in an echo command is to print multiple pages of text on a single line. Here’s an example:
This will print the text on separate pages.
Use \n To Add Newline
The \n character allows you to add a new line to your output. Here’s an example:
The \n character can also be used in combination with other escape characters, such as \t for a tab, to create more formatted output.
Here’s an example:
Use \t for Horizontal Tab Space
The \t character gives you the behavior of horizontal tab spaces.
Here’s an example:
Here, the character adds horizontal tab spaces between the texts.
Use \v for Vertical Tab Space
The \v character gives you the behavior of vertical tab spaces, as shown:
Here, the character adds vertical tab spaces between the texts.
Use \\ to Display Backslash
The \\ character allows you to display the backslash \ character.
Here’s an example:
Use -E to Ignore Escape Characters
Unlike the -e option which lets you interpret escape characters, the E option ignores all the escape characters in an argument.
Here, the texts are printed as they are passed in, and the escape characters are ignored.
The Echo Command: Some Practical Examples
Adding and Overwriting Texts in a File
The echo command can be used to add new text to a file or overwrite the previous texts in a file. This operation is carried out using the > or >> operators. The > operator is used for overwriting the file content, while the >> operator is used for adding new texts to the file.
Here’s an example:
This creates a new file named ‘test.txt’ and adds the text if the file doesn’t exist, or simply adds the new text to the file if it already exists.
To check the content of the file:
You can overwrite the text in the file above.
The file text changes to the following:
Displaying Variables in the Terminal
Using the echo command, you can display the different variables you declared as well as environment variables on your terminal. Here’s an example:
Here, you declared a new variable called ubay and assigned good to it. Its value is printed out by adding the $ sign in front of the variable, which tells echo that it is a variable and not a text.
You can also use the echo command to display the value of multiple variables at once by separating them with a space. For example, if you have a second variable new that contains the value “hello”, you can display both ubay and new by running the following command:
Printing Files of a Specific Kind
You may sometimes want to look for a specific file type in a specific directory. In this case, the echo command will come in handy, as it can be used to display files of a specific type that exist in a directory.
Consider the following example where you display all the png files in your Desktop directory:
This displays all of the files with the extension png in your current directory. When searching for documents in your folders, this can be helpful because you can easily filter out if that document type exists. You can also display all .txt files in your directory.
Here’s an example:
You can also search for a specific file type in your directory by piping the echo command to the grep command.
Here is an example of how you can do this:
In this example, the echo command is used to specify the text “myfile.txt”, which is then piped to the grep command using the pipe operator | . The grep command is used with the -r option, which tells it to search recursively through all directories and subdirectories for the specified text.
This command will search for the file named “myfile.txt” within the current directory and all of its subdirectories, and output the results of the search to the terminal.
Using echo as an Alternative to the ls Command
The echo command can also be used in place of the ls command to list all the contents of a directory.
Here’s an example:
Here, you listed all the contents in the desktop directory.
You can also list only the directories and exclude files:
This list only contains folders and does not include files in the desktop directory, which is useful when searching for folders in your directory.
To print the names of only the files in the current directory, you can use the following:
This will only print the names of files that do not end in a forward slash (/), indicating that they are files and not directories.
Piping echo With Other Commands
The echo command can be piped with other commands to perform various actions using the pipe operator | . Some examples of piping the echo command with other commands are:
Using echo With the tee Command
To output the result of a command and save it to a file, the echo command can be piped with the tee command:
To append the output of a command to an existing file, the echo command can be piped with the tee command and the -a flag:
Using echo With the tr Command
To pass the output of a command as input to another command, the echo command can be piped with the desired command:
Using echo With the grep Command
To search for a specific string in the output of a command, the echo command can be piped with the grep command:
This would search for the text “world” within the output of the echo command, which in this case is the string “Hello World”. The grep command will return the string “World” since it matches the search pattern.
You can use the -n option with grep to include the line number in the output:
This would return “1:world”, indicating that the string “world” was found on line 1 of the output.
Changing Output Colors
By default, the color of the output of the echo command matches the terminal theme. You might be in a situation where you need to change the colors, such as when writing a script and you need to show whether a step was successful, which is usually displayed in green, or warn them about a step in which red is used.
The color output is changed by formatting them using the ANSI escape codes for each color.
Here’s an example:
Here, you used \033[ which represents ESC[ , followed by the ANSI escape color code for Red 0;31 , and then an m to change the color of the output.
You can also write a Bash script to perform an action and change color. Here’s an example:
In this script, we first set a variable called number to the value we want to find the square root of. Then, we use the echo command to pass the sqrt function and the value of number to the bc command, which calculates the square root and stores the result in a variable called result . Finally, we use the echo command to display the result in the terminal and change its color to green.
Save this script to a file , say, myscript.sh, make it executable with the chmod command: chmod +x myscript.sh , and then run it with the ./ command : ./myscript.sh to see the green message in the terminal.
Here are the ANSI escape color codes for some colors:
Colors | Codes |
---|---|
Red | 0;31 |
Yellow | 1;33 |
Green | 0;32 |
Blue | 0;34 |
White | 1;37 |
Conclusion
You should now have working knowledge on how to use the echo command. In this tutorial, you learned about the echo command and its options, such as -n to omit trailing lines, -e to interpret escape characters, and -E to ignore escape characters.
The tutorial also explained the various scenarios in which the echo command can be used, such as adding and overwriting texts in a file, outputting declared variables to the terminal, and printing files of a specific kind in a directory. You’ve also learned how the command can be piped with other commands using the pipe operator and how to customize the output colors.
Earthly makes CI/CD super simple
Fast, repeatable CI/CD with an instantly familiar syntax – like Dockerfile and Makefile had a baby.
Ubaydah is a backend engineer who has built APIs using a variety of languages and frameworks such as Python Django, Golang, and Javascript. She also has experience writing technical documentation and articles. She enjoys passing on technical knowledge, reading, and learning about new technologies.
Bala is a technical writer who enjoys creating long-form content. Her areas of interest include math and programming. She shares her learning with the developer community by authoring tutorials, how-to guides, and more.