Bash Scripting – Displaying Interactive Messages
Other Learning Articles that you may like to read
Free Courses We Offer
Paid Training Courses we Offer
Most shell commands produce their own output, which is displayed on the console monitor where the script is running. Many times, however, you will want to add your own text messages to help the script user know what is happening within the script. You can do this with 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 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 following output:
$ ./test1
The time and date are:
Mon Feb 21 15:41:13 EST 2014
Let’s see who’s logged into the system:
Christine tty2 2014-02-21 15:26
Samantha tty3 2014-02-21 15:26
Timothy tty1 2014-02-21 15:26
user tty7 2014-02-19 14:03 (:0)
user pts/0 2014-02-21 15:21 (:0.0)
$
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 this:
echo -n “The time and date are: ”
You 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 now looks like this:
$ ./test1
The time and date are: Mon Feb 21 15:42:23 EST 2014
Let’s see who’s logged into the system:
Christine tty2 2014-02-21 15:26
Samantha tty3 2014-02-21 15:26
Timothy tty1 2014-02-21 15:26
user tty7 2014-02-19 14:03 (:0)
user pts/0 2014-02-21 15:21 (:0.0)
$
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.