Using echo command in Linux


The echo is a built-in Linux/Unix command which is used to display the line of text or string on standard output or a file. Most commonly it is used in scripts to display the output or result of some other commands.

In this article, we will see the usage of the echo command in Linux.

How to use echo command in Linux

The syntax of using the echo command in Linux is given below –

echo [option] string

Where you can use the following options –

-n –  Do not output the trailing newline

-e – Enable the interpretation of backslash escapes

-E – This will disable the interpretation of backslash escapes (default)

If the interpretation of backslash escapes is enabled the following sequence will be recognized by the echo command –

\\ –  display a backslash

\a – alert

\b – backspace

\c – produce no further output

\e – escape

\f – form feed

\n – newline

\r – carriage return

\t – horizontal tab

\v – vertical tab

How to display a line of text on standard output

The most basic use of the echo command is to print a string on standard output. Use the following command to print a string –

echo Hello World!

See the output in the image below –

Print the text with newline

You can create a new line by using the \n option with the echo command. Please remember to use the option -e to enable the interpretation of backslash escapes.

The example to print text with newline is given below –

echo -e "This is an example of using \necho command in Linux"

Now see the output of this command –

Similarly, you can use /t for horizontal and /v for vertical tab in the text.

Declaring a variable and displaying its value using the echo command

The following statement declares a variable x and assigns some value to it.

x=15

Now to print the value of x on standard output use –

echo The value of x is $x

Now see the output of this command –

Print the list of all files and directories in your current working directory

The echo command can also be used as an alternative to the ls command to list files and directories in a directory. Use the following command to see the list of all files and directories in your current working directory

echo *

Or use the given command to see text files only –

echo *.txt

Conclusion

This is how you can use the echo command in Linux. If you have a query then leave it in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.