Automating with expect

expect does not come by default on all Linux distributions. You may have to install the expect package with your package manager (apt-get or yum).

Expect has three main commands:

The following example spawns the backup script and then looks for the patterns *folder* and *file* to determine if the backup script is asking for a folder name or a filename. It will then send the appropriate reply. If the backup script is rewritten to request files first and then folders, this automation script still works.

#!/usr/bin/expect  
#Filename: automate_expect.tcl 
spawn ./backup .sh  
expect { 
  "*folder*" { 
     send "notes\n" 
     exp_continue 
   } 
  "*type*" { 
     send "docx\n" 
     exp_continue 
  } 
} 

Run it as: 

$ ./automate_expect.tcl 

The spawn command's parameters are the target application and arguments to be automated.

The expect command accepts a set of patterns to look for and an action to perform when that pattern is matched. The action is enclosed in curly braces.

The send command is the message to be sent. This is similar to echo -n -e in that it does not automatically include the newline and does understand backslash symbols.