Displaying Messages - Shell Scripting

Most shell commands produce their own output, which is displayed on the console monitor where the script is running. Many times though you will want to add your own text messages to help the script user know what is happening within the script. This is done using the echo command. The echo command can display a simple text string if you add the string following the command:

$ echo This is a test
This is a test
$

Notice that by default you don’t need to use quotes to delineate the string you’re displaying.
However, sometimes this can get tricky if you are using quotes within your string:

$ echo Let’s see if this’ll work
Lets see if thisll work
$

The echo command uses either double or single quotes to delineate text strings. If you use them within your string, you need to use one type of quote within the text, and the other type to delineate the string:

$ echo "This is a test to see if you’re paying attention"
This is a test to see if you’re paying attention
$ echo ’Rich says "scripting is easy".’
Rich says "scripting is easy".
$

Now all of the quotation marks appear properly in the output.
You can add echo statements anywhere in your shell scripts where you need to display additional information:

$ cat test1
#!/bin/bash
# This script displays the date and who’s logged on
echo The time and date are:
date
echo "Let’s see who’s logged into the system:"
who
$

When you run this script, it produces the output:

$ chmod u+x test1
$ ./test1
The time and date are:
Mon Sep 24 20:09:35 EST 2007
Let’s see who’s logged into the system:
rich :0 2007-09-24 18:23 (console)
rich pts/1 2007-09-24 18:24
rich pts/0 2007-09-24 18:42
barbara pts/2 2007-09-24 19:30
katie pts/3 2007-09-24 19:39
$

That’s nice, but what if you want to echo a text string on the same line as a command output? You can use the -n parameter for the echo statement to do that. Just change the first echo statement line to:

echo -n "The time and date are: "

You’ll need to use quotes around the string to ensure that there’s a space at the end of the echoed string. The command output begins exactly where the string output stops. The output will now look like:

$ ./test1
The time and date are: Mon Sep 24 20:11:35 EST 2007
Let’s see who’s logged into the system:
rich :0 2007-09-24 18:23 (console)
rich pts/1 2007-09-24 18:24
rich pts/0 2007-09-24 18:42
barbara pts/2 2007-09-24 19:30
katie pts/3 2007-09-24 19:39
$

Perfect! The echo command is a crucial piece of shell scripts that interact with users. You’ll find yourself using it in many situations, especially when you want to display the values of script variables. Let’s look at that next.


All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Shell Scripting Topics