Echo Text Control in Bash
Introduction to Echo Text Control in Bash
Welcome to your first lesson on text processing with Bash! In this lesson, we'll dive deep into the echo command. As you know, the echo command in Bash allows you to print text to the terminal. Though it may seem simple, the echo command is powerful and versatile, and mastering it is essential for formatting messages, debugging scripts, and more. Now, let's dive into the advanced text manipulation with echo.
Suppressing New Lines
By default, echo adds a newline character at the end of the output. However, you can suppress this behavior using the -n option.
Output:
The first two echo commands by default add a new line at the end of the output. This results in "Greetings" and "Universe" being printed on new lines. By including -n before "Hello", the new line is suppressed resulting in "Hello" and "World" being printed on the same line.
Escape Characters
Escape characters are special sequences in a string that denote a particular character that cannot be easily typed or is otherwise reserved. In Bash, escape characters are introduced with a backslash (). They allow you to include characters in your output that have special meanings or are not readily available on the keyboard. To include escape characters in a string, you use the syntax:
When you use the -e option with the echo command, these escape sequences are interpreted and displayed as their corresponding special characters.
Some common escape characters are:
\nfor a new line\tfor a tab\\\for a backslash\"for a quote
Let's look at some examples!
Adding New Lines
\n is an escape character that represents a newline in a string. When used with the echo -e, it instructs the terminal to move the cursor to the beginning of the next line, effectively splitting the text at that point into multiple lines. Here's an example:
Output:
Using \n, you can now print multiple lines with a single echo command.
In contrast, omitting -e in the above statement would display:
