Linux logo

The echo Command in Linux

The echo is a basic command found in many operating systems offering a command line. It’s often used in scripts, batch files, and as part of individual commands; anywhere you might want to insert text. Many command shells like bash, ksh, and csh implement echo as a built-in command.

Echo in Linux

The echo command in Linux is used to show line of text/string which is passed as an argument. This is a built-in command that’s largely used in shell scripts and batch files to output status text to the screen or a file.

How to use echo command in Linux

The general syntax for using the echo command in Linux:

$ echo [OPTION]… [STRING]…

For displaying the string by echo:

$ echo [string]

Let us have a look at a few example commands to understand how it works.

An example of displaying string using echo

For displaying text or string, you simply need to provide the string as follows:

$ echo just a test message

That’s it.

Further Reading:  A little about Vim and how to search in it
Adding/Appending text in a file example

If you want to use the echo command to append some text to a file then this is just like above plus giving the file name where you want to add text. For example:

$ echo just a test message >> file_name

This should add the “just a test message” to the file_name file.

Remove newline by –n option example

By default, the echo command output ends with a newline character. However, if you would like, you can change this behavior using the -n command line option.

For example:

$ echo -n "How to disable newline"
how to create a new line example

By using \n, you may add a new line from where it’s used.

$ echo -e "Hello \nand \nWelcome"
An example of tab spaces using \t

By using \t option, you may add horizontal tab spaces. For example:

$ echo -e "Hello \tand \tWelcome"
Declare a variable and display its value

Declare a variable and display its value. The example below shows hows:

$ a=5

$ echo variable a = $a


variable a = 5
Give a sound alert by \a

By using the option ‘\a’ — alert return with backspace interpreter ‘-e’ to produce sound.

$ echo -e "Hello and  \aWelcome Guys"
How echo handles backslash escapes?

When used in default mode, the echo command does not treat backslash escapes as special characters and hence doesn’t translate them in any special manner. For example, the following command will not add backspace but display as it is:

$ echo “Hello /band welcome”

 

Further Reading:  How to Shutdown Linux by Using Commands

In order to make it work, you may use the –e option i.e.:

$ echo -e “Hello /band welcome”
The \v option example

The \v option is used to make vertical tab spaces. An example command:

$ echo -e "Hello \vand \vWelcome
Echo * example

Echo * command will print all files/folders, like ls command.

$ echo *
Print specific files

Print files of a particular type. For example, if you want to print all ‘.pdf’ files, use the following command.

$ echo *.pdf