Some Noticeable Information
Echo is a vital command that allows us to get visible output from shell scripts and can include variables, filenames, and directories.
There are two versions of echo available: one integrated into the Bash shell and another as a binary executable.
Echo serves multiple purposes, including writing text to the terminal window, enabling dynamic output using variables, incorporating command output, formatting text using backslash-escaped characters, listing files and directories, and writing to files.
The echo command is an ideal tool for displaying formatted text on the terminal window, offering more than just static content. It allows the inclusion of shell variables, filenames, and directories. Additionally, echo can be redirected to generate text files and log files. Follow this straightforward guide below to learn more.
What Does Echo Do?
Echo is responsible for repeating what it has been instructed to repeat, making it a crucial and straightforward function. Without echo, obtaining visible output from shell scripts would be impossible.
Although it may not possess an overwhelming amount of additional features, there is a high likelihood that echo encompasses certain capabilities that you may be unaware of or have simply overlooked.
There are Two Versions of echo
Most Linux systems provide two versions of echo. The Bash shell has its own echo built into it, and there's a binary executable version of echo as well.
We can see the two different versions by using the following commands:
type echo
whereis echo
The type command informs us about the nature of the command passed to it as an argument, whether it is a shell builtin, binary executable, alias, or function. It specifies that echo is a shell builtin. Once it finds an answer, type ceases searching for additional matches. Consequently, it does not disclose the existence of other commands with the same name in the system. However, it indicates the first one it finds, which becomes the default choice when executing that command.
The whereis command searches for the binary executable, source code, and man page of the specified command-line parameter. It excludes shell builtins as they are incorporated within the Bash executable. According to the whereis command, the binary executable for echo can be found in the /bin directory.
To use that version of echo you would need to explicitly call it by providing the path to the executable on the command line:
/bin/echo --version
The shell builtin doesn't know what the --version command-line argument is, it just repeats it in the terminal window:
echo --version
The examples shown here all use the default version of echo, in the Bash shell.
Writing Text to the Terminal with echo
To write a simple string of text to the terminal window, type echo and the string you want it to display:
echo My name is Dave.
The text is repeated for us. But as you experiment, you'll soon discover that things can get slightly more complicated. Look at this example:
echo My name is Dave and I'm a geek.
The terminal window shows a > sign, indicating it is waiting for a command. Pressing Ctrl+C will take you back to the command prompt. What caused this situation?
The presence of a single quote or apostrophe in the word "I'm" caused confusion for the echo command. It interpreted the single quote as the beginning of a quoted text section. As there was no closing single quote, echo remained in a waiting state, expecting additional input that would include the missing single quote it was anticipating.
To include a single quote in a string, the simplest solution is to wrap the whole string within double quote marks:
echo "My name is Dave and I'm a geek."
Using double quotation marks to enclose your text is a valuable tip. This practice effectively defines the boundaries of the parameters being passed to the echo function in scripts. It greatly facilitates the process of reading and troubleshooting scripts.
What if you want to include a double quote character in your text string? It's simple: just place a backslash \ before the double quote mark (with no space between them).
echo "My name is Dave and I'm a \"geek.\""
This wraps the word "geek" in double quote marks for us. We'll see more of these backslash-escaped characters shortly.
Using Variables With echo
Up until now, our approach has been to write fixed text to the terminal window. However, we can enhance the dynamism of our output by incorporating variables with the echo command. This allows us to insert values provided by the shell into our output. To create a basic variable, we can utilize the following command:
A variable named "my_name" has been initialized with the value "Dave". The variable can be used within echo statements by using the variable name preceded by a dollar sign $ to indicate it as a variable.
There is a caveat. If you have enclosed your string in single quotation marks, the echo command will interpret everything literally. To ensure that the variable value is displayed instead of the variable name, use double quotation marks.
echo "My name is $my_name"
echo "My name is $my_name"
Somewhat aptly, that's worth repeating:
Using single quote marks results in the text being written to the terminal window in a literal fashion.
Using double quote marks results in the variable being interpreted — also called variable expansion — and the value is written to the terminal window.
Using Commands With echo
To incorporate the output of a command into a string written to the terminal window, we can use the echo command. By treating the command as a variable and enclosing it in parentheses, we can achieve this. It is recommended to first use the command on its own before using it with echo. This allows for identification and correction of any syntax issues before including it in the echo command. Additionally, if the echo command does not produce the expected result, it indicates that the issue lies with the echo syntax, as the command's syntax has already been validated.
So, try this in the terminal window:
date +%D
And, satisfied that we're getting what we expect from the date command, we'll integrate it into an echo command:
echo "Today's date is: $(date +%D)"
Note the command is inside the parentheses and the dollar sign $ is immediately before the first parenthesis.
Formatting Text With echo
The -e option allows us to use backslash-escaped characters for text formatting. Here are the available backslash-escaped characters and their functions:
\a: Produces an alert sound (historically known as BEL).
\b: Writes a backspace character.
\c: Abandons any further output.
\e: Writes an escape character.
\f: Writes a form feed character.
\n: Writes a new line.
\r: Writes a carriage return.
\t: Writes a horizontal tab.
\v: Writes a vertical tab.
\\: Writes a backslash character.
Let's use some of them and see what they do.
echo -e "This is a long line of text\nsplit across three lines\nwith\ttabs\ton\tthe\tthird\tline"
The text is split into a new line where we've used the \n characters and a tab is inserted where we've used the \t characters.
echo -e "Here\vare\vvertical\vtabs"
Similar to \n new line characters, a vertical tab \v shifts the text to the line below. However, the \v vertical tab differs from \n in that it does not initiate the new line at column zero. Instead, it occupies the present column.
The \b backspace characters move the cursor back one character. If there is more text to be written to the terminal, that text will overwrite the previous character.
echo -e "123\b4"
The "3" is over-written by the "4".
The \r carriage return character causes echo to return to the start of the current line and to write any further text from column zero.
echo -e "123\r456"
The "123" characters are overwritten by the "456" characters.
The \a alert character will produce an audible "bleep." It uses the default alert sound for your current theme.
echo -e "Make a bleep\a"
The -n option, which is not a backslash-escaped sequence, has an impact on the visual presentation of the text. It ensures that a newline character is not added at the end of the text. As a result, the command prompt is immediately displayed after the text is written to the terminal window.
echo -n "no final newline"
Using echo With Files and Directories
Using echo as a substitute for ls can be considered a less effective approach. There are limited alternatives available when using echo in this manner. For higher accuracy and enhanced control, it is advisable to utilize ls along with its wide range of options.
This command lists all of the files and directories in the current directory:
echo *
This command lists all of the files and directories in the current directory whose name starts with "D" :
echo D*
This command lists all of the ".desktop" files in the current directory:
echo *.desktop
Yeah. This isn't playing to echo's strengths. Use ls.
Writing to Files with echo
We can redirect the output from echo and either create text files or write into existing text files.
Using the > redirection operator will create the file if it does not already exist. If the file does exist, the content from echo will be inserted at the beginning of the file, replacing any previous content.
On the other hand, by using the >> redirection operator, if the file does not exist, it will be created. The output from echo will be appended to the end of the file without overwriting any existing content.
echo "Creating a new file." > sample.txt
echo "Adding to the file." >> sample.txt
Display the content of the "sample.txt" file in a terminal window.
The first command creates a new file and inserts text into it. The second command appends a line of text at the end of the file. The cat command displays the file's contents in the terminal window. Variables can also be used to provide additional information in the file. For instance, if the file is a logfile, we can add a timestamp using the following command.
Note the single quote marks surrounding the parameters for the date command; they prevent the space between the parameters from being mistakenly interpreted as the end of the parameter list, making sure that the parameters are correctly passed to the date function.
To write the start time of the log file to a text file called "logfile.txt," use the following command:
echo "Logfile started: $(date +'%D %T')" > logfile.txt
cat logfile.txt
The command to display the contents of the logfile.txt file in a terminal window is:
logfile.txt in a terminal window" style="display:block;height:auto;max-width:100%;" data-img-url="https://static1.howtogeekimages.com/wordpress/wp-content/uploads/2019/10/21-2.png" />
Our logfile is created for us and cat shows us that the datestamp and timestamp were both added to it.
That's echo's Repertoire
A simple command, but indispensable. If it didn't exist, we'd have to invent it.
Editor's P/S
The echo command is a powerful tool that allows users to get visible output from shell scripts. It can be used to write text to the terminal window, enable dynamic output using variables, incorporate command output, format text using backslash-escaped characters, list files and directories, and write to files. The echo command is an ideal tool for displaying formatted text on the terminal window, offering more than just static content. It allows the inclusion of shell variables, filenames, and directories. Additionally, echo can be redirected to generate text files and log files.
Echo is a versatile command that can be used for a variety of purposes. It is a powerful tool that can be used to enhance the functionality of shell scripts and to automate tasks.