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.

#!/bin/bash
# Default new line
echo "Greetings"
echo "Universe"

# Suppress new line
echo -n "Hello"  # Prints "Hello" without newline
echo "World"    # Prints "World" on the same line as "Hello"

Output:

Greetings
Universe

HelloWorld

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:

echo -e "..."

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:

  • \n for a new line
  • \t for 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:

#!/bin/bash
echo -e "This is line 1.\nThis is line 2." 

Output:

This is line 1.
This is line 2.

Using \n, you can now print multiple lines with a single echo command.

In contrast, omitting -e in the above statement would display:

This is line 1.\nThis is line 2.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal