Skip to content
ImagineWorld

Automating Scripts with here Documents and expect

node_idnode-book_the-ultimate-linux-shell-scripting-guide_chapter-12-automating-scripts-with-here-documents-and-expect
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleAutomating Scripts with here Documents and expect
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 12 — Automating Scripts with here Documents and expect

Section titled “Chapter 12 — Automating Scripts with here Documents and expect”

So, exactly where is here? Well, I suppose that it’s just where I happen to be, or from your own perspective, wherever you happen to be. The bigger mystery, which nobody seems to have figured out, is why a very useful shell scripting construct has such a strange name.

A here document, which can also be called a here script or a heredoc, isn’t really a document, and it has nothing to do with anyone’s current location. But, as you shall soon see, it’s extremely useful in a number of different ways, such as in automating your scripts.

The second automation method I’ll show you is expect, which is a scripting environment with its own scripting language.

Topics in this chapter include:

  • Using here Documents
  • Automating responses with expect

All right, let’s get ready to automate!

Technical Requirements

You can use any Linux virtual machine for this chapter. Also, as always, you can grab the script and text files from GitHub by doing:

git clone https://github.com/PacktPublishing/The-Ultimate-Linux-Shell-Scripting-Guide.git

Using here Documents

A here document is a block of code that you place into a script to perform a certain task. Yeah, I know, I said the same thing about functions. But, here documents are completely different. They’ve been around since the early days of Unix, and can be used in various different programming languages.

Formatting note: The accepted Unix and Linux convention for writing out the term “here document” is to do so in all lower-case letters. That can get a bit confusing, though. So, to eliminate the confusion, I’ll just italicize the term throughout the rest of this book, like this: here document.

Here documents work by providing another way to redirect input into a particular command. The code that performs this redirection is enclosed by a pair of limit strings, which look something like this:

command << _EOF_
...
Code to execute or data to display
...
_EOF_

is a special type of redirector. It takes input from whatever code or text is between wo limit strings, which in this case are called EOF. It’s traditional to use either EOF or EOF as limit strings, but you can actually use pretty much any text string you want, as long as they’re the same at both the beginning and end of the code block, and also as long as they don’t conflict with the names of any variables or functions. In fact, it can often help make the script more readable if you give descriptive names to your limit strings. (Some tutorials that you’ll find use the term token instead of limit string, but it’s still the same thing.)

Instead of using << as the redirector, you can also use <<-, like this:

command <<-_EOF_
...
Code to execute or data to display
...
_EOF_

Adding the dash prevents any leading tab characters from indenting any displayed text. (Leading spaces will still indent the text, but tabs won’t. I’ll explain more about this in just a bit.) This makes it so that you can indent the code in the script to make it more readable, without causing the output to be indented.

Here are some of the things that you can do with here documents:

  • Display multi-line comments from a shell script.
  • Create a simple look-up directory.
  • Automate the creation of documents, such as web content files or reports.

Your here documents can work with either static or dynamic data. Let’s start with the static ones, since they’re the simplest.

Creating here Documents with Static Data

There may be times when you’ll want your scripts to display some sort of a multi-line message when users invoke them. This message could be a help message, a copyright message, or a licensing message. You could do that with a series of echo commands, which would look something like this:

#!/bin/bash
echo "This software is released under the GNU GPL 3 license."
echo "Anyone who uses this software must respect the terms"
echo "of this license."
echo
echo "GNU GPL 3 is a license that aims to protect software freedom."

This works, but if you need to display a long message, typing in many individual echo commands can get a bit tedious. Using a here document to display the message can make things much easier. Here’s how that looks in the here-doc1.sh script:

#!/bin/bash
cat << licensing
This software is released under the GNU GPL 3 license.
Anyone who uses this software must respect the terms
of this license.
GNU GPL 3 is a license that aims to protect software freedom.
licensing

In this case, I’m using licensing as the limit strings, instead of the more traditional EOF. This way, I can tell at a glance what the here document is doing for me. Here’s what happens when I run the script:

Terminal window
[donnie@fedora ~]$ ./here-doc1.sh
This software is released under the GNU GPL 3 license.
Anyone who uses this software must respect the terms
of this license.
GNU GPL 3 is a license that aims to protect software freedom.
[donnie@fedora ~]$

As you see, the text that’s between the two licensing strings gets redirected into the cat command, which then displays the text on screen.

There may be times when you’ll need to choose a license for any free-as-in-freedom software or shell scripts that you need to create. There are many free software licenses from which to choose, and you’ll need to choose the one that best fits your needs. Basically though, you can classify the various licenses as either permissive or non-permissive. Permissive licenses, such as the MIT and BSD licenses, allow licensed code to be embedded into proprietary software, and don’t require that the source code for the finished product be provided to the customer. (This is why Apple can include FreeBSD code in its proprietary OS X and macOS operating systems.) Non-permissive licenses, such as the various GNU Public Licenses, prohibit the use of licensed code in proprietary software, and require that software vendors make the source code of the finished product available to customers. Anyway, you can read all about the various free software licenses here: https://opensource.org/licenses/

By the way, MIT stands for Massachusetts Institute of Technology, BSD stands for Berkeley Software Distribution, and GNU is a recursive acronym that stands for GNU is not Unix.

There may be times when you’ll want to indent the code in your here documents to make the script more readable. That’s not the case with this here-doc1.sh script, but let’s pretend that it is. Let’s create the here-doc1-tabs.sh script, and make it look like this:

#!/bin/bash
cat << licensing
This software is released under the GNU GPL 3 license.
Anyone who uses this software must respect the terms
of this license.
GNU GPL 3 is a license that aims to protect software freedom.
licensing

This is the same as here-doc1.sh, except that I placed two tabs in front of the “This software..” line, one tab in front of the “Anyone who..” and “..of this license” lines, and three blank spaces in front of the “GNU GPL 3..” line. Watch what happens when I run this new script:

Terminal window
donnie@fedora:~$ ./here-doc1-tabs.sh
This software is released under the GNU GPL 3 license.
Anyone who uses this software must respect the terms
of this license.
GNU GPL 3 is a license that aims to protect software freedom.
donnie@fedora:~$

Now, let’s say that we want to leave the tabs and the blank space in the script, but we don’t want the tabs to show up in the output. All we need to do is to change the << to <<-, as you see here in the here-doc1-tabs-dash.sh script:

#!/bin/bash
cat <<- licensing
<!-- page: 341 (printed 335) -->
This software is released under the GNU GPL 3 license.
Anyone who uses this software must respect the terms
of this license.
GNU GPL 3 is a license that aims to protect software freedom.
licensing

Now, watch what happens when I run it:

Terminal window
donnie@fedora:~$ ./here-doc1-tabs-dash.sh
This software is released under the GNU GPL 3 license.
Anyone who uses this software must respect the terms
of this license.
GNU GPL 3 is a license that aims to protect software freedom.
donnie@fedora:~$

This time, all of the lines that begin with tabs in the script now output text that is flush with the left margin. However, the line that begins with three blank spaces outputs text with three blank spaces.

As I mentioned in the opening paragraph of this section, using <<- instead of << prevents any leading tabs in your here document from showing up in the script’s output. But, it allows any leading blank spaces to show up.

It’s important to remember that you can’t have any blank spaces in front of the closing limit string. If I were to insert a blank space in front of the closing licensing string in the here-doc1.sh script, I would get an error message that looks something like this:

Terminal window
[donnie@fedora ~]$ ./here-doc1.sh
./here-doc1.sh: line 10: warning: here-document at line 3 delimited by end-of-
file (wanted `licensing')
This software is released under the GNU GPL 3 license.
Anyone who uses this software must respect the terms
of this license.
GNU GPL 3 is a license that aims to protect software freedom.
licensing
[donnie@fedora ~]$

Of course, this isn’t what you want.

This here-doc1.sh script isn’t very useful as-is, because the only thing it does is display a message. So normally, you’d place the rest of your code after the here document. One cool trick you can do is to place a sleep command and a clear command immediately after the here document, so that the opening message will display for a specified number of seconds before the main part of the script begins to execute.

Also, you’re not limited to using this type of here document at the beginning of the script. You can place one anywhere in the script where you might need to impart some sort of information to a user.

Next, let’s create a simple look-up directory with a list of phone numbers. Here’s the here-doc2.sh script that does that:

#!/bin/bash
grep $1 <<directory
lionel 555-1234
maggie 555-2344
telyn 555-4555
cleopatra 555-4818
vicky 555-1919
charlie 555-2020
frank 555-2190
goldie 555-8340
directory
exit

In this script, I’m passing a name as a positional parameter to the grep command. The phone directory entries are between the two directory limit strings. Note that in this script, I didn’t place a blank space between the << and the first limit string, as I did in the previous example. This just shows you that the blank space is optional, and that either way works. Anyway, here’s what happens when I look up Lionel’s phone number:

Terminal window
[donnie@fedora ~]$ ./here-doc2.sh lionel
lionel 555-1234
[donnie@fedora ~]$

If your here document includes any metacharacters that cause the shell to take some sort of action, you’ll need to escape them with a backslash, as you see here in the here-doc3.sh script:

#!/bin/bash
grep $1 <<donations
lionel \$5.00
maggie \$2.50
katelyn \$10.00
cleopatra \$7.35
vicky \$20.00
charlie \$3.00
frank \$8.25
goldie \$9.05
donations
exit

Surrounding strings that contain special characters with quotes won’t work, because here documents treat all quote symbols as literal characters.

This method of dealing with special characters works, but there’s an easier way. Just place a backslash in front of the limit string, like this:

#!/bin/bash
grep $1 <<\donations
lionel $5.00
maggie $2.50
katelyn $10.00
cleopatra $7.35
vicky $20.00
charlie $3.00
frank $8.25
goldie $9.05
donations
exit

You can also surround the limit string with a pair of single quotes, like this:

#!/bin/bash
grep $1 <<'donations'
lionel $5.00
maggie $2.50
katelyn $10.00
cleopatra $7.35
vicky $20.00
charlie $3.00
frank $8.25
goldie $9.05
donations
exit

Although these latter two methods work well and are easier than having to escape every special character individually, they can mess you up if you need to use a $ to obtain the value of a variable. That’s because everything will get treated as a literal string, even if you don’t want that. To see how that works, let’s look at the here-doc3-wrong.sh script:

#!/bin/bash
grep $1 <<\donations
lionel $5.00
maggie $2.50
katelyn $10.00
cleopatra $7.35
vicky $20.00
charlie $3.00
frank $8.25
goldie $9.05
$1
donations
exit

You see that I’ve placed a backslash in front of the opening donations limit string in order to escape all of the metacharacters.I′vealsoplacedametacharacters. I've also placed a1 on a line by itself, just before the closing donations limit string. What I want to happen is for the value of the $1 positional parameter to print out at the end of the output. But, watch what happens when I run this:

Terminal window
donnie@fedora:~$ ./here-doc3-wrong.sh lionel
lionel $5.00
donnie@fedora:~$

Now, let’s remove the backslash from in front of the opening limit string, and escape all of the $ metacharacters individually, except for the one that’s in the positional parameter. This script should now look like this:

#!/bin/bash
grep $1 <<donations
lionel \$5.00
maggie \$2.50
katelyn \$10.00
cleopatra \$7.35
vicky \$20.00
charlie \$3.00
frank \$8.25
goldie \$9.05
$1
donations
exit

When I run the script now, the value of the $1 at the bottom should print out, like this:

Terminal window
donnie@fedora:~$ ./here-doc3-wrong.sh lionel
lionel $5.00
lionel
donnie@fedora:~$

The lesson here is that even though some of our programming shortcuts can be very handy, it might not always be appropriate to use them.

That pretty much covers the static angle. Now, let’s get dynamic.

Creating here documents with Dynamic Data

In addition to including normal data in here documents, you can also include the programming constructs and commands that you’d use normally. Then, just redirect the output into a dynamically-generated document. Here’s the here-doc4.sh script, which shows a simple example of redirecting output into a .html file:

#!/bin/bash
title="System Information for $HOSTNAME"
current_date=$(date +%F)
cat <<-_system-info_ > sysinfo.html
<title>
$title
</title>
<body>
$(uname -opr) <br>
Updated on: $current_date
</body>
_system-info_

To prove that it works, just open the resultant file in a web browser. The web page should look something like this:

Of course, I’m keeping things simple here by creating a very simple document with only a few simple HTML tags to format it. But, if you’re clever with HTML coding, you can make the document as fancy as you want.

In case you’re wondering, HTML stands for Hypertext Markup Language. Long ago, when the public Internet was brand new and I still had a full head of hair, the only way to create websites was to hand-code them in HTML. (Ah, yes. Those were the days.)

You can also create documents in other formats. For example, if you want to create a .pdf document, there are a couple of ways to do that. The simplest way is to install the appropriate pandoc packages from either your Linux or FreeBSD distro’s repository. (It’s also available for macOS, but you’ll need to download the installer package from the Pandoc website.) The slight catch with this is that you’ll also need to install a PDF engine, and some PDF engines aren’t available for all distros. Your best bet is to stick with the pdflatex engine, because it’s available for pretty much all Linux distros, as well as for FreeBSD and macOS. (Sadly, there are no pandoc or PDF engine packages available for OpenIndiana.) your Fedora virtual machine, install pandoc and the pdflatex engine with this simple command:

Terminal window
[donnie@fedora ~]$ sudo dnf install pandoc-pdf

’ is same command will also install pandoc on Red Hat Enterprise Linux-type distros, but you’ll first need to install the EPEL repository. On AlmaLinux and Rocky Linux, install EPEL like this:

Terminal window
[donnie@rocky ~]$ sudo dnf install epel-release

On Debian or Ubuntu-type distros, just do:

Terminal window
donnie@ubuntu2204:~$ sudo apt install pandoc texlive-latex-recommended

On FreeBSD do:

Terminal window
donnie@freebsd-1:~$ sudo pkg install hs-pandoc texlive-full

Note that for FreeBSD, I’m assuming that you’ve already installed the sudo package, added yourself to the wheel group, and have configured visudo. If you haven’t, you can just log in as the root user for now, in order to perform the installation. Also, if you haven’t done so already, be sure to install the bash package, and create a symbolic link to bash in the /bin/ directory, like this:

Terminal window
donnie@freebsd-1:~$ sudo ln -s /usr/local/bin/bash /bin/bash

The here-doc scripts that I’ve shown you so far will work on the /bin/sh shell that FreeBSD uses by default, but I’ll soon be showing you a script that will require actual bash.

For macOS, you’ll need to download the Pandoc and MacTeX installers from their respective websites.

If you’re running OpenIndiana, you’re out of luck, because there are no pandoc or pdf engine packages available for it. That’s okay though, because as you’ll see in a few moments, I’ve made the upcoming demo script so that it will still run on it.

In any case, the installation of pandoc and the pdf engine packages takes a while, because a lot of dependencies also need to be installed. So, you might as well go grab your favorite beverage while you’re waiting.

Once you have pandoc installed, on everything except for OpenIndiana, add the following lines to the end of your here-doc4.sh script:

pandoc -o sysinfo.pdf sysinfo.html
rm sysinfo.html

Now when you run the here-doc4.sh script, you’ll end up with the sysinfo.pdf file as the result. You can either open the file in your favorite document viewer, or add a line of code to have the file automatically print out. Assuming that you’ve installed the appropriate printer drivers and have set a default printer, the command that you would add to the end of the script to do this would be:

lpr sysinfo.pdf

Tip I showed you how to set up a default printer and use lpr in Chapter 7, Text Stream Filters - Part 2.

The reason I’m using HTML in this here document example is simply because HTML is so easy. If you’re clever with any other document markup language, such as Postscript, Markdown, Troff or LaTeX, feel free to use one of them in place of HTML. In all cases, you can convert the resultant file to a .pdf file, if that’s what you need. On the other hand, if you don’t need anything this fancy, you could omit all markup language tags, and just save your output to a plain-text file. Then, use the appropriate text stream filters, such as fmt and pr, to prepare the file for print out. The possibilities are only limited by your own imagination.

Now that we’ve covered the basics, let’s look at something that’s a bit more complex.

For this section, I created the sysinfo.lib file, which you can download from Github. Then, copy it to your /usr/local/lib/ directory. Finally, download the system-info.sh script from Github. I can’t show you either the library file or the shell script in their entirety here, but I can show you some snippets and provide some explanation.

In this demo, you’ll see what I had to do to make this script work on Linux, FreeBSD, macOS, and OpenIndiana.

The first two functions in the library, the show_uptime() and drive_space() functions, are quite easy. Each of them executes just one simple system information command and then adds some HTML tags, as you see here:

show_uptime() {
echo "<h2>System uptime</h2>"
echo "<pre>"
uptime
echo "</pre>"
}
drive_space() {
echo "<h2>Filesystem space</h2>"
echo "<pre>"
df -P
echo "</pre>"
}

I used df -P in the drive_space() function so that the output would format properly on macOS. (The -P isn’t needed for Linux, FreeBSD, or OpenIndiana, but it doesn’t hurt anything to have it.)

Now, take a look at the home_space() function:

Terminal window
home_space() {
echo "<h2>Home directory space by user</h2>"
echo "<pre>"
echo "Bytes Directory"
if [ $(uname) = SunOS ]; then
du -sh /export/home/* | sort -nr
elif [ $(uname) = Darwin ]; then
du -sh /Users/* | sort -nr
else
du -sh /home/* | sort -nr
fi
echo "</pre>"
}

This function uses the du utility to report the amount of drive space that each user’s home directory is using. The slight problem is that OpenIndiana and macOS don’t have users’ home directories in the /home/ directory, as Linux and FreeBSD do. So, I included code that would determine where du is to look, as determined by the operating system.

Next are the open_files() and open_files_root() functions, which report the number of files that the apache and root users have open. Both functions are the same except for the specified user, so I’ll just show you one of them here:

Terminal window
open_files_root() {
echo "<h2>Number of open files for root</h2>"
echo "<pre>"
lsof -u root | wc -l
echo "</pre>"
}

You see that it’s very simple, and just pipes the lsof -u output into wc -l to count the number of open files for the specified user.

The next function is open_files_users(), which is a bit more complex. I once again need to take the difference in home directory locations into account, which you see here in the first half of the function:

open_files_users() {
echo "<h2> Number of open files for normal users</h2>"
if [ $(uname) = SunOS ]; then
cd /export/home
elif [ $(uname) = Darwin ]; then
cd /Users
else
cd /home
fi
}

The second half of the function is a for loop that reads the names of the users’ home directories, and then uses those names in the lsof commands. But, there’s another wrinkle here that we need to iron out. It’s that if your Linux machine has the /home/ directory mounted on its own partition, and the partition is formatted with either the ext3 or ext4 filesystem, there will be a lost+found directory that’s not a user’s home directory. On macOS, you’ll see a Shared directory that’s also not a user’s home directory. If you try to use either of these two directory names as an argument for lsof, you’ll receive an error. So, I had to add some code to exclude those two directory names from being used, as you see here:

for user in *
do
if [[ $user != "lost+found" ]] && [[ $user != "Shared" ]]; then
echo "There are $(lsof -u $(id -u $user) | wc -l) open files
for $user. "
echo "<br>"
fi
done
cd
}

You see that I’m using the && sequence as an and operator so that I can place both test conditions into just one if..then construct. One reference that I found states that the and (&&) and or (||) operators work better with the [[..]] test construct than they do with the [..] test construct. However, I just tested the function both ways, and both work for me here. I’ve also shown you something that I don’t remember having shown you before. That is, you can nest one command substitution construct within another command substitution construct, as you see in the first echo line.

Finally, there’s the system_info() function, which again will work differently on different operating systems. That’s because system information is in the /etc/os-release file on Linux and FreeBSD and in the /etc/release file on OpenIndiana. On macOS, there’s no kind of release file at all, so I had to use another method. Anyway, here’s the top portion of the function, which is for Linux and FreeBSD:

system_info() {
# Find any release files in /etc
if [ -f /etc/os-release ]; then
os=$(grep "PRETTY_NAME" /etc/os-release)
echo "<h2>System release info</h2>"
echo "<pre>"
echo "${os:12}"
echo "<br>"
uname -orp
echo "</pre>"
}

If the /etc/os-release file is present, the value of the os variable will be the PRETTY_NAME line from that file. The echo ”${os:12}” line strips off the PRETTY_NAME part, so that only the actual version name of the Linux or FreeBSD distro is left. I then used the uname -orp command to show the system information that I want everyone to see. (I’ll let you look in the uname man page to see what all of the option switches are doing.)

The next part of the function is for OpenIndiana, as you see here:

elif [ $(uname) = SunOS ]; then
echo "<h2>System release info</h2>"
echo "<pre>"
head -1 /etc/release
echo "<br>"
uname -orp
echo "</pre>"

The /etc/release file on OpenIndiana isn’t the same as the /etc/os-release file on Linux and FreeBSD. So, I used the head -1 command to read the first line of the file, which contains the version name of the distro.

The final portion of this function is for OS X/macOS, as you see here:

elif [ $(uname) = Darwin ]; then
echo "<h2>System release info</h2>"
echo "<pre>"
sw_vers
echo "<br>"
uname -sprm
echo "</pre>"
<!-- page: 351 (printed 345) -->
else
echo "Unknown operating system"
}

Since there’s no release file of any kind, I used the sw_vers command instead, which is only available on OS X and macOS. The output from this command looks like this:

Terminal window
Donald-Tevaults-Mac-Pro:~ donnie$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.14.6
BuildVersion: 18G9323
Donald-Tevaults-Mac-Pro:~ donnie$

And yes, that is a very old version of the Mac operating system. But, the machine is a mid-2010 model Mac Pro, and this is the newest version that it will run. (Well, it can run a more recent version, but I’ll have to perform some unnatural acts that aren’t authorized by Apple in order to do it. This involves installing the OpenCore Legacy Patcher, which will modify the Mac’s bootloader so that you can install a newer version of macOS. Be aware though that things can go wrong with this, which could render your Mac unbootable. Trust me, I know.)

I also had to use a different combination of option switches for uname, because macOS uses a different implementation of uname. (Again, look at the man page for uname on your Mac machine to see what the option switches are doing.)

That’s it for the function library file. Now, we need to look at the system_info.sh script that uses this library. Here’s the top part:

#!/bin/bash
# sysinfo_page - A script to produce an HTML file
. /usr/local/lib/sysinfo.lib
title="System Information for $HOSTNAME"
right_now=$(date +"%x %r %Z")
time_stamp="Updated on $right_now by $USER"

The shebang line, which we first talked about in Chapter 8, Basic Shell Script Construction, has to be #!/bin/bash, because some of the alternate shells that are referenced by #!/bin/sh aren’t compatible with some of the programming constructs that I need to use. So, if you’re running this script on either Alpine Linux or FreeBSD, you’ll need to install bash.

The rest of this top portion just reads in the function library and sets up the variables that I’ll use in the rest of the script. So, there’s nothing hard there.

The next portion consists of the here document, which inserts the proper HTML tags and invokes several functions, as you see here:

cat <<-_system-info_ > sysinfo.html
<html>
<!-- page: 352 (printed 346) -->
<head>
<title>
...
...
$(home_space)
$(open_files_root)
$(open_files_users)
</body>
</html>
_system-info_

So again, there’s nothing hard here.

The final portion of the script converts the .html output file to a .pdf file, if the pandoc package is installed. If it’s not, then it will just leave the .html file alone. Here’s how that looks:

if [[ -f /usr/local/bin/pandoc ]] || [[ -f /usr/bin/pandoc ]]; then
pandoc -o sysinfo.pdf sysinfo.html
rm sysinfo.html
fi
exit

As much as I’d like to always have a .pdf file, that’s not possible on OpenIndiana. As I’ve mentioned before, pandoc isn’t in the OpenIndiana repository. The only other .pdf creation tool I’ve seen for OpenIndiana is groff, but that involves using a whole different markup language.

When you run this script, you’ll need to use your sudo privileges in order to access information about other users. Also, don’t be alarmed if you get error messages about directories that the script can’t access, because that happens even with sudo. For example, here on my Fedora workstation, the script can’t access the pCloud directory that’s in my home directory, because it’s a mount point for a remote drive.

This is all I’ll say about here documents for now. But, in Chapter 20, Shell Script Portability, I’ll show you more about them, and will also show you more ways to make scripts run across a variety of operating systems and shells. For now though, let’s look at what to expect next.

Automating Responses with expect

There may be times when you’ll need to run a script that stops multiple times to prompt you for some sort of input. That can get a bit tedious after a while, especially if you need to run the script multiple times on multiple servers or workstations. Wouldn’t it be nice to automate the responses? Well, with all due respect, you can with expect.

So, what is expect? Well, it’s a programming environment, similar to what you have with bash. If you have an interactive shell script that expects certain responses, you can use expect to automatically send the correct responses. Let’s begin with the simplest of examples. First, create the interactive_script.sh script, like so:

#!/bin/bash
echo "Hello. What is your name?"
read reply
echo "What's your favorite operating system?"
read reply
echo "How many cats do you have?"
read reply
echo "How many dogs do you have?"
read reply

When you run this script, it will pause at each read reply command so that you can type in a response. Of course, that’s not a big deal for this simple script. But now, pretend that you’ve written some sort of software testing script that’s long and complex, and that requires the software tester to constantly enter responses. Unless you enjoy pain, and I doubt that you do, you probably don’t want to be glued to your workstation, constantly entering responses for those long tests. So, your best bet is to automate the process, and your best bet for that is to use expect. You should find it already installed on a Mac, but for everything else you’ll have to install it yourself.

Verify whether it’s installed by doing:

Terminal window
which expect

If it’s not installed, it should be in your distro’s repository as the expect package. On FreeBSD, you’ll need to take the additional step of creating a symbolic link, so that you won’t have to modify your scripts to run on FreeBSD. Do it like this:

Terminal window
donnie@freebsd-1:~ $ sudo ln -s /usr/local/bin/expect /bin/expect
donnie@freebsd-1:~ $

Now that it’s installed, create the interactive_script.exp companion script. The easiest way to do that is to use autoexpect, like this:

Terminal window
[donnie@fedora ~]$ autoexpect -f interactive_script.exp ./interactive_script.sh
autoexpect started, file is script.exp
Hello. What is your name?
Donnie
What's your favorite operating system?
Linux
How many cats do you have?
1
How many dogs do you have?
0
autoexpect done, file is script.exp
[donnie@fedora ~]$

As you see, autoexpect runs the original interactive_script.sh script, and prompts you for responses. The responses get saved to the interactive_script.exp script that you specified with the -f option. Note that if the original script is in your home directory, you’ll need to precede its name with a ./ so that autoexpect can find it. The entire interactive_script.exp script is too long to show, so I’ll show you some snippets, along with some explanation.

The first thing to note is that expect scripts have their own shebang line, which looks like this:

#!/bin/expect -f

The -f means that responses will be read from this file.

The next thing I want to show you is the spawn command, which looks like this:

spawn ./interactive_script.sh

When I run the expect script, it will automatically start the original shell script.

Next, let’s look at how the expect script provides responses:

expect -exact "Hello. What is your name?\r"
"
send -- "Donnie\r"
expect -exact "Donnie\r
What's your favorite operating system?\r
"
send -- "Linux\r"
expect -exact "Linux\r
How many cats to you have?\r
"
send -- "1\r"
expect -exact "1\r
How many dogs do you have?\r
"
send -- "0\r"

The expect commands duplicate the questions from the original shell script. By including the -exact option, the questions must be identical to the originals. The first expect command only asks for my name, and all of the others both send back the response and then pull in the next question. The \r at the end of each line provides a carriage return, so that the next response or question will show on a new line. (Note that this isn’t the Windows-type of carriage return that can cause so much trouble in text files or configuration files.)

The very last line of the expect script looks like this:

expect eof

As you might expect, this indicates the End of File.

349

Another cool thing about autoexpect is that it automatically sets the executable permission on the script files that it generates. So, you won’t have to do that yourself. Now, here’s what happens when I run this expect script:

Terminal window
[donnie@fedora ~]$ ./interactive_script.exp
spawn ./interactive_script.sh
Hello. What is your name?
Donnie
What's your favorite operating system?
Linux
How many cats to you have?
1
How many dogs do you have?
0
[donnie@fedora ~]$

All of the questions got answered automatically, without me having to interact with the script at all.

Now, as cool as autoexpect is, there are some drawbacks. First, it only comes with the expect packages that are in the repositories for the various Linux distros. For some strange reason, it’s not available for FreeBSD, OpenIndiana, or macOS. So, if you ever need to create an expect script for any of those operating systems, your best bet is to create it on a Linux machine, and then transfer it over to the non-Linux machine. Secondly, if you use it with a software installation script that uses curl or wget to download the software, the output from curl or wget that shows the status of the download will become part of the expect script. You’ll need to remove all of that from the expect script by hand so that the script will work correctly. And lastly, you can’t expect autoexpect to do everything. Sometimes, you’ll just need to hand-code the expect scripts yourself.

Security Implications with expect

There are lots of ways to use expect, but in my own opinion, it’s most useful for the automation of software testing or installation. Most other tutorials you’ll find show you how to automate either ssh login sessions or scp file transfers, but you need to be careful if you use expect for anything like that. The problem is that the password of the destination machine will get stored in plain-text format in the expect script, which is also plain text. Making things even worse, is that some of these tutorials have you access the root user account of the destination machine like this.

Now, my own general rule is to never enable the root user account when setting up a server, as long as the operating system installer gives me that choice. When setting up something like FreeBSD, where that isn’t a choice, I like to install and configure sudo as my first post-installation step, and then disable the root account. However, there are times when it’s necessary to enable the root user account, as well as to use scp to transfer files to the root user’s account. If that is ever necessary, it’s more secure to disable password authentication on the server, and instead use key-based authentication.

Even then, I only feel comfortable accessing the root user account from within a tightly-controlled local network, rather than from across the Internet. Having said all this, if you still ever find it necessary to store plain-text ssh passwords in an expect script, be sure to store the script in a location that only you or trusted members of your team can access. (But hopefully though, you’ll find another way to do things that won’t require placing passwords into the expect scripts.)

The only other thing I’ll say about expect is that it is a vast topic, and at least one entire book has been written about it. (I’ll leave a link for it in the Further Reading section for anyone who might be interested.)

Okay, let’s wrap this chapter up and move on.

Summary

In this chapter, I’ve shown you some cool tricks to help automate your scripts. I first showed you here documents, and how to use them in a few different ways. Then, I showed you expect, which is a whole scripting language unto itself. I showed you some ways to use expect, and then talked about some of its security implications.

In the next chapter, I’ll show you some scripting tricks for ImageMagick. I’ll see you there.

Questions

  1. What is a here document?

    a. It shows your current location.

    b. It’s a block of code for a specific purpose.

    c. It’s a type of executable script.

    d. It’s a block of static data.

  2. Which of the following statements is true?

    a. A here document uses its own scripting language.

    b. A here document can only be used in bash scripts.

    c. A here document can be used with a variety of programming and scripting languages.

    d. A here document can only be used to display comments or other static data.

  3. How do you define a here document?

    a. Place #!/bin/here in the script as the shebang line.

    b. Surround the entire here document with a pair of double quotes.

    c. Surround the entire here document with a pair of single quote.

    d. Surround the entire here document with a pair of limit strings.

  1. Which of the following statements is true?

    a. You can use autoexpect for any situation, and then use the resultant expect scripts without any editing.

    b. The expect scripts that autoexpect creates might need to be hand-edited to make them work correctly.

    c. You can use autoexpect on any operating system, including Linux, FreeBSD, macOS, and OpenIndiana.

    d. You should never use autoexpect for anything.

  2. What is one implication of using expect?

    a. When using expect to automate ssh logins or scp transfers, the password for the destination server will be stored in plain-text within the expect script.

    b. There are no implications.

    c. It’s not very efficient.

    d. It’s too hard to create an expect script.

Further Reading