How it works...

Let's write a script that reads input interactively for an automation example:

#!/bin/bash 
# backup.sh 
# Backup files with suffix. Do not backup temp files that start with ~ 
read -p " What folder should be backed up: " folder 
read -p " What type of files should be backed up: " suffix 
find $folder -name "*.$suffix" -a ! -name '~*' -exec cp {} \   
    $BACKUP/$LOGNAME/$folder 
echo "Backed up files from $folder to $BACKUP/$LOGNAME/$folder" 

Let's automate the sending of input to the command:

$ echo -e "notes\ndocx\n" | ./backup.sh 
Backed up files from notes to /BackupDrive/MyName/notes

This style of automating an interactive script can save you a lot of typing during developing and debugging. It also insures that you perform the same test each time and don't end up chasing a phantom bug because you mis-typed.

We used echo -e to produce the input sequence. The -e option signals to echo to interpret escape sequences. If the input is large we can use an input file and the redirection operator to supply input:

$ echo -e "notes\ndocx\n"  > input.data
$ cat input.data
notes
docx

You can manually craft the input file without the echo commands by hand–typing. Consider this example:

$ ./interactive.sh < input.data

This redirects interactive input data from a file.

If you are a reverse engineer, you may have played with buffer overflow exploits. To exploit them we need to redirect a shell code such as \xeb\x1a\x5e\x31\xc0\x88\x46, which is written in hex. These characters cannot be typed directly on the keyboard as keys for these characters are not present. Therefore, we use:

echo -e \xeb\x1a\x5e\x31\xc0\x88\x46"

This will redirect the byte sequence to a vulnerable executable.

These echo and redirection techniques automate interactive input programs. However, these techniques are fragile, in that there is no validity checking and it's assumed that the target application will always accept data in the same order. If the program asks for input in a changing order, or some inputs are not always required, these methods fail.

The expect program can perform complex interactions and adapt to changes in the target application. This program is in worldwide use to control hardware tests, validate software builds, query router statistics, and much more.