Install expect Command in Linux with Practical Examples

Try this guide with our instant dedicated server for as low as 40 Euros

expect bash

Whether you are a seasoned Linux professional or a budding enthusiast, efficient workflows and unattended execution are key to maximizing productivity. Automating repetitive tasks like software installations, system backups, security scans, and data processing frees users to tackle more critical issues that require human intervention.

The Linux expect command plays a crucial role in this context. 

It is a powerful tool specifically designed to automate interactive applications in Linux. By leveraging a scripting language, expect automates interactions with programs that normally require user input. This eliminates the need for manual intervention, saving users time and effort, and ensuring consistency in tasks.

In this tutorial, we will discuss the expect commands and how to install the utility on your Linux machine. Finally, we will demonstrate the capabilities of the utility with several examples. 

Let’s start with an overview of the expect command.

Table Of Contents

  1. What is expect Command
  2. Linux expect Command Syntax
  3. Linux expect Command Options
  4. The Prerequisites To Working With the expect Command
  5. How to Install Linux expect Command?
    1. Ubuntu and Debian-based Systems
    2. CentOS, Fedora, and Red Hat-based Systems
    3. Arch Linux and Manjaro
    4. openSUSE
  6. Linux expect Command Examples
    1. Example #1: Basic expect Use
    2. Example #2: expect with Variables
  7. Conclusion
  8. FAQs

What is expect Command

The expect utility uses the standard TCL as the scripting language. This makes it a powerful tool in Unix-like operating systems for automating interactions with programs that require user input. You can use it for automating tasks that involve password prompts and other command-line interfaces that do not support scripting directly.

Key features of expect command are:

  • Automating interactive applications
  • Pattern matching
  • Control over the timing of execution

Linux expect Command Syntax

The basic syntax of the expect command is:

# expect [options] script

Here, 

script: This file contains the commands that expect executes to interact with the target program.

options: These flags modify how expect behaves or interacts with the scripts and processes.

Linux expect Command Options

expect command accommodates various options to customize scripts to fit various automation needs. The following table summarizes the common expect command options:

Linux expect Command Options

Now that you have an understanding of the basics of expect command including its syntax, let us go into the details of the utility’s installation process. 

The Prerequisites To Working With the expect Command

Before diving into the installation process and the application scenarios, ensure you have the following:

  • A system running a mainstream Linux distribution
  • A user account with sudo or administrator privileges

How to Install Linux expect Command? 

The exact steps in installing expect depends on your Linux distribution. However, we will discuss the general steps in installing expect on popular Linux distribution options.

Ubuntu and Debian-based Systems

Follow these steps for installing expect on your system.

Open the terminal and run the following command to update the system’s package list.

# sudo apt update 

Once the package list is updated, install expect by running this apt install command.

# sudo apt install expect

sudo apt install expect

CentOS, Fedora, and Red Hat-based Systems

If you’re using CentOS or another Red Hat-based distribution, use yum or dnf to install expect.

For CentOS 7 or RHEL 7 (or lower versions), run the following command:

# sudo yum install expect

Alternatively, if you are on CentOS 8, Fedora, or RHEL 8 (and later versions), run this command:

# sudo dnf install expect

Arch Linux and Manjaro

For Arch-based distributions, use pacman to install expect:

# sudo pacman -S expect

openSUSE

For openSUSE, use zypper to install expect.

# sudo zypper install expect

Once you execute the appropriate command for your distribution, expect should be installed and ready to use. 

You can verify the installation and version by executing the following:

# expect -v

The output displays the version of expect if installed successfully.

Linux expect Command Examples

Now that you have installed expect on your system, let’s discuss a few practical examples of how to use the command for automating everyday tasks. .

Example #1: Basic expect Use

Consider the scenario where you have a simple shell script named greet.sh that prompts for the user’s name and prints a greeting. 

The script is as follows:

#!/bin/bash

echo "Please enter your name:"

read name

echo "Hello, $name!"

cat greet.sh

This is a basic script that uses the read command to store the user input in a variable named name and produce greetings when prompted.

Now our goal is to automate the process of entering names using the expect command. To achieve this, we will create an expect script by following these steps:

Step #1: Create a Script

Open a text editor of your choice (Vim or Nano) and create a file named auto_greet.exp.

Add the following lines to this script.

#!/usr/bin/expect -f 

# Start the greeting script

spawn ./greet.sh

# Wait for the name prompt

expect "Please enter your name:"

# Send the name

send "RedSwitches\r"

# Optionally wait for the greeting to verify it works correctly

 expect "Hello, RedSwitches!"

# Allow the script to finish 

expect eof

Here,

#!/usr/bin/expect -f: Indicates the interpreter for the script (expect) and the -f flag implies it to read commands from the following file.

spawn ./greet.sh: Starts the greet.sh script that is the target of the expect script.

expect “Please enter your name”: Waits for the greet.sh script to output.

send “RedSwitches\r”: Sends your desired name (here RedSwitches) followed by a newline character (\r) to simulate pressing Enter.

 expect “Hello, RedSwitches!”: It is the optional expect statement that allows you to verify the script’s output by waiting for the greeting with your name.

Step #2: Run the expect Script

Once you have created the script, ensure both greet.sh and your expect script (auto_greet.exp) have executable permissions:

# chmod +x greet.sh

# chmod +x auto_greet.exp

chmod +x greet.sh

Next, execute the expect script with the following command:

# ./auto_greet.exp

Step #3: Output

Executing the auto_greet.exp script will automatically run greet.sh, displaying the name you passed in the auto_greet.exp script (replacing “YourNameHere”), and displaying the greeting without requiring manual input.

Therefore, the output of running the auto_greet.exp script will be: 

spawn ./greet.sh

Please enter your name:

RedSwitches

Hello, RedSwitches! 

auto greet.exp

As you can see, expect automates the interaction by waiting for specific text and responding appropriately. By using expect command, you can automate tests, script interactions, and also routine tasks involving command-line programs that require user inputs.

Example #2: expect with Variables

Leveraging variables in an expect script, as demonstrated in the previous greet.sh script, can significantly enhance the flexibility and adaptability of automation tasks.

Now, let’s modify the previous example to incorporate variables. This allows the script to handle names dynamically, which is useful when the interaction requires customization based on user input, input from other scripts, or other similar conditions.

Start With the Original Script

First, let’s recall the original Bash script greet.sh that prompts for the user’s name and prints a greeting:

#!/bin/bash

echo "Please enter your name:"

read name

echo "Hello, $name!"

Start With the Original Script

The Enhanced expect Script 

Now, let us write an expect script that uses variables to interact with greet.sh

This script dynamically handles the input names, making it reusable for different names without modifying the script.

#!/usr/bin/expect -f

# Define a variable for the name
set name "RedSwitches"


# Start the greeting script

spawn ./greet.sh

# Wait for the prompt
expect "Please enter your name:"

# Send the name stored in the variable
send "$name\r"

# Wait to see the output to confirm it worked correctly
expect "Hello, $name!"

# End the script
expect eof

The Enhanced expect Script

Here,

  • set name “RedSwitches”: Defines a variable named name. It sends the name to the script. Replace RedSwitches with your desired name and the script handles it accordingly.
  • spawn ./greet.sh: This command initiates the greet.sh script.
  • expect “Please enter your name:”: The script waits for the prompt Please enter your name before proceeding.
  • send “$name\r”: Sends the value of the name variable followed by a Carriage Return (\r), simulating pressing the Enter key.
  • expect “Hello, $name!”: Once the name is sent, the script waits for the expected greeting, which includes the name it just sent. This step confirms that the greet.sh script has received the input correctly and has responded as expected.
  • expect eof: This command waits for the end of the file (EOF), which in this context means it waits for the greet.sh script to finish executing.

Conclusion

The expect command is a powerful tool for automating routine tasks in Linux, saving time and reducing the potential for human error. By understanding and utilizing the expect command, you can enhance your system administration efficiency significantly. 

FAQs

Q. What is expect command and how can it be used in Linux?

The expect command is a tool command language that can be used in Unix or Linux systems to automate interactive tasks. It is often used for scripting tasks that require user input and responses.

Q. How can I install the expect command on my Linux system?

To install expect command on a Linux system, you can use a package manager such as apt-get or yum. For example, on Ubuntu, run, sudo apt-get install expect.

Q. How can I run an expect script in Linux?

You can run an expect script in Linux by saving it to a file (e.g., script.exp) and then executing it using the expect command followed by the script file name: expect script.exp.

Q. What is a pty and why is it important in expect scripting?

A pty, or pseudo-terminal, is a virtual terminal used by programs to interact with a terminal-like device. In expect scripting, using a pty allows for interactive communication with programs as if they were being run in a terminal.

Q. How can I debug an expect script?

To debug an expect script, use the exp_internal 1 command at the beginning of your script. This command enables debug output to help you see what is happening at each step of the script execution.

Q. What are some common terms used in Expect scripting?

Some common terms used in expect scripting include set timeout, send_user, exp_continue, set password, send “password\r”, set environment variables, generate scripts, system administrator, and regular expression -o.

Try this guide with our instant dedicated server for as low as 40 Euros