#!/usr/bin/perl use warnings; use strict; use Expect; print("STDIN is not a terminal, running xterm\n"), exec ('xterm', '-e', $^X, $0, @ARGV) unless -t STDIN; print "Surely running in a terminal\n"; my $expect = Expect::->spawn("/bin/sh") or die "bash: $!\n"; $expect->expect(1,"\$ "); # expect a command line prompt $expect->send("ls\n"); $expect->expect(1,"ls\r\n"); # sh echoes the entered command, so I have to expect() it back # need to play with $expect->slave->stty() to get rid of \r $expect->expect(1,"\$ "); # expect another command line prompt meaning that the command succeeded my $result = $expect->before(); # catch everything in between the echoed "ls" and new prompt $expect->send("exit\n"); # terminate the shell properly $expect->soft_close; print "Gathered output: BEGIN\n$result\nEND\n";