How to use the echo command in shell scripting

How to use the echo command in shell scripting

In this tutorial I will show you, how to use the echo command in shell scripting.

In Linux and Unix, the echo command is used to write text in files or at the standard output (stdout) and to display the values of variables.

Examples of using echo:

$ echo "Hello"

$ PI=3.14
$ echo $PI

The -e option in echo enables the interpretation of special text contstants for string manipulation:

  • \n  -> newline
  • \t  ->  horizontal tab
  • \v  ->  vertical tab
  • \r  ->  carriage return
  • \b  ->  backspace
  • \f  ->  form feed
  • \c  ->  produce no output
  • \a  ->  ding

Using echo to write text:

Text formatting with echo:

Display text on new line: echo -e “\nText here” or echo -n “Text here”
$ echo -e "\nHello World"

$ echo -n "Hello World"

Insert vertical tab in text string: echo -e “\tText here”
$ echo -e "\tHello World"

Backspace one character in the text: echo -e “\bTText here“
$ echo -e "\bHello World" #This will display ello World

$ echo -e "\bHHello World" #This will display Hello World

These options can be combined together: echo -e “\nThis\tis\ta\bt\ttext”

Displaying the variable values with echo:

With: echo $x
$ x=5
$ echo $x

It is recommended to use quotes echoing a variable’s value: echo “$x” for preserving the word splitting or the whitespaces. The quotes protect the special characters inside the variables. Read more here.

Was this Tutorial helpful? Help others share on Facebook, Twitter, and Google Plus!

Enjoyed this video?
How to use the echo command in shell scripting
"No Thanks. Please Close This Box!"