Home > Text Processing & Search > echo

echo Command Guide: Printing Text and Variables

The `echo` command is used to display a string of text to the standard output (usually the terminal screen). It is widely used in shell scripts to show messages to the user, check variable values, append content to files, and more. This guide will help you learn the basic usage and useful options of the `echo` command.

echo Overview

`echo` does exactly as its name suggests: it 'echoes' its arguments back to the screen. It's an essential tool for basic I/O operations in shell scripting, such as debugging, user notifications, and file creation.

Key Roles of echo

The `echo` command is primarily used for the following purposes:

Main Use Cases

  • Displaying Messages: Shows information, warnings, or error messages to the user.
  • Checking Variable Values: Verifies the current values of environment or shell variables.
  • Writing to Files: Uses redirection (`>` or `>>`) to write or append text to a file.
  • Script Debugging: Aids in debugging by printing variable values at specific points in a script's execution flow.
  • Generating Automated Reports: Used to output the results or intermediate status of a script to a file.

Key echo Command Options

Although simple, the `echo` command offers several useful options and escape sequences to control its output.

1. Basic Output Options

2. Escape Sequences (with -e)

Generated command:

Try combining the commands.

Description:

`echo` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

Explore various use cases of the `echo` command to master basic shell scripting techniques like printing text, checking variables, and manipulating files.

Basic String Output

echo "Hello, Linux!"

Prints the string `Hello, Linux!` to the screen, followed by an automatic newline.

Print Environment Variable Value

echo $HOME

Outputs the value of the `HOME` environment variable, which stores the current user's home directory path.

Multi-line Output (with escape characters)

echo -e "Line 1\nLine 2\nLine 3"

Uses the `-e` option and the `\n` escape character to print text across multiple lines.

Concatenate Text without Newline

echo -n "Hello "
echo "World!"

Links two `echo` commands using the `-n` option to print them on a single line. (Run `echo -n "Hello "` followed by `echo "World!"`)

Write to File (Overwrite)

echo "Hello, file!" > output.txt

Writes the string `"Hello, file!"` to the file `output.txt`. If the file exists, its content will be overwritten.

Append to File

echo "Appending new line." >> output.txt

Appends the string `"Appending new line."` to the end of `output.txt`. A new file is created if it doesn't exist.

Print with Tabs

echo -e "Name:\tJohn\nAge:\t30"

Outputs a name and age, separated by a tab.


Same category commands