tags:

views:

76

answers:

5

I am using a interactive command line program in a Linux terminal running the bash shell. I have a definite sequence of command that I input to the shell program. The program writes its output to standard output. One of these commands is a 'save' command, that writes the output of the previous command that was run, to a file to disk.

A typical cycle is:

$prog
$$cmdx
$$<some output>
$$save <filename>
$$cmdy
$$<again, some output>
$$save <filename>
$$q
$<back to bash shell>
  • $ is the bash prompt
  • $$ is the program's prompt
  • q is the quit command for prog
  • prog is such that it appends the output of the previous command to filename

How can I automate this process? I would like to write a shell script that can start this program, and cycle through the steps, feeding it the commands one by one and, and then quitting. I hope the save command works correctly.

A: 
echo "cmdx\nsave\n...etc..." | prog

..?

+4  A: 

I recommend you use Expect. This tool is designed to automate interactive shell applications.

schot
+3  A: 

If your command doesn't care how fast you give it input, and you don't really need to interact with it, then you can use a heredoc.

Example:

#!/bin/bash
prog <<EOD
cmdx
save filex
cmdy
save filey
q
EOD

If you need branching based on the output of the program, or if your program is at all sensitive to the timing of your commands, then Expect is what you want.

Tristan
That served my purpose. I wasn't sure where standard output would go.
sauparna
A: 

For simple use cases you may use a combination of subshell, echo & sleep:

# in Terminal.app
telnet localhost 25
helo localhost
ehlo localhost
quit

(sleep 5; echo "helo localhost"; sleep 5; echo "ehlo localhost"; sleep 5; echo quit ) | 
   telnet localhost 25 
yabt
A: 

I use Expect to interact with the shell for switch and router backups. A bash script calls the expect script with the correct variables.

for i in ; do expect_script.sh $i ; exit

This will ssh to each box, run the backup commands, copy out the appropriate files, and then move on to the next box.

Sable