views:

427

answers:

1

Is there a way to parse input and output from bash commands in an interactive terminal before they reach the screen ? I was thinking maybe something in .bashrc, but I'm new to using bash.

For example:

  • I type "ls /home/foo/bar/"
  • That gets passed through a script that replaces all instances of 'bar' with 'eggs'
  • "ls /home/foo/eggs/" gets executed
  • The output gets sent back to the replace script
  • The output of the script is sent to the screen
+2  A: 

Yes. Here's something I wrote for my own use, to wrap old command line Fortran programs that ask for file-paths. It allows escaping back to the shell for e.g. running 'ls'. This only works one way, i.e. intercepts user-input and then passes it on to a program, but gets you most of what you want. You can adapt it to your needs.

#!/usr/bin/perl

# shwrap.pl - Wrap any process for convenient escape to the shell.
# ire_and_curses, September 2006

use strict;
use warnings;


# Check args
my $executable = shift || die "Usage: shwrap.pl executable";

my @escape_chars = ('#');                    # Escape to shell with these chars
my $exit = 'exit';                           # Exit string for quick termination

open my $exe_fh, "|$executable @ARGV" or die "Cannot pipe to program $executable: $!";

# Set magic buffer autoflush on...
select((select($exe_fh), $| = 1)[0]);

# Accept input until the child process terminates or is terminated...
while ( 1 ) {
   chomp(my $input = <STDIN>);

   # End if we receive the special exit string...   
   if ( $input =~ m/$exit/ ) {
      close $exe_fh;
      print "$0: Terminated child process...\n";
      exit;            
   }

   foreach my $char ( @escape_chars ) {   
      # Escape to the shell if the input starts with an escape character...
      if ( my ($command) = $input =~ m/^$char(.*)/ ) {
         system $command;
      }
      # Otherwise pass the input on to the executable...
      else {
         print $exe_fh "$input\n";
      }
   }
}
ire_and_curses
Is there a way to get things like arrow keys and history to work with your script?
Annan
Not that I know of. These are shell builtins, and assume the shell is running interactively (which it's not in this case). If you want more functionality than this, then you're really looking at writing your own shell - which isn't as hard as it sounds. See e.g. http://linuxgazette.net/111/ramankutty.html
ire_and_curses