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"
Hello

$ PI=3.14
$ echo $PI
3.14

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
5

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.

Share and Enjoy

  • Twitter
  • Facebook
  • Google Plus
  • Email
  • RSS
Tagged with: , , , , ,
Posted in The Linux and Unix Articles!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Subscribe

  

Subscribe to get the latest Linux news and how to guides directly on your e-mail!