echo
Description
echo is a standard Unix utility that displays a line of text in the terminal.
The command syntax is:
echo [flags] [text]
Flags
Here are some flags associated with echo.
-e: enable interpretation of backslash escapes.-E: disable interpretation of backslash escapes.-n: do not output the trailing newline.--help: get more information about the command
-e
Description:
With the -e option, the echo command will interpret escape characters such as \t and \n.
Usage:
Let us assume we want to display the word Hello World into the terminal such that the words are separated by a tab. We will do this as:
echo -e "Hello\tWorld"
Since -e is the default flag, we can omit it and still get the same result.
echo "Hello\tWorld"
Output:
Hello World
-E
Description:
With the -E option, the echo command will interpret escape characters such as \t and \n as characters and not escape characters.
Usage:
Taking above example with -E flag:
echo -E "Hello\tWorld"
Output:
Hello\tWorld
-n
Description:
With the -n option, the echo command will not output the trailing new line. This is useful for when you're writing multiple echo statements in a script as described in the example section.
Usage:
echo -n "Hello World"
Output:
Hello World
--help
Description:
With the --help option, the echo command will show other flags and options for the command that are not commonly used.
Usage:
echo --help
Examples
Let's say you are writing a shell script that displays a progress message with a series of dots to indicate a task is in progress. You want the dots to appear on the same line, without a newline character between them.
Without
-nflag: Assume the contents of atestfile are as follows:echo "Task in progress" echo "..."Executing the file, the output will be:
Task in progress ...With
-nflag: Assume the contents of atestfile are as follows:echo -n "Task in progress" echo "..."Executing the file, the output will be:
Task in progress...Printing words in a separate line
echo -e "Hello\nWorld"The output will be:
Hello WorldPrinting the escape characters as is:
echo -E "Hello\nWorld"The output will be:
Hello\nWorld
Additional Information
echo command is frequently used to redirect user input to a file such as:
echo "Save this file" > file.txt
Now the content of file.txt will be:
Save this file
Exercises
Use the
--helpflag and print a\into the terminal.Create a file with your name with the
echocommand and the>redirect operator.Create a file with two lines
HelloandWorldusing a singleechocommand and the>redirect operator.