一种解析终端输出/输入的方法? (.bashrc?)

时间:2009-08-08 13:01:09

标签: linux bash command-line terminal

有没有办法在交互式终端中的bash命令到达屏幕之前解析输入和输出?我想在.bashrc中可能有些东西,但我是新手使用bash。

例如:

  • 我输入“ls / home / foo / bar /”
  • 通过一个脚本传递,该脚本用'eggs'替换'bar'的所有实例
  • “ls / home / foo / eggs /”执行
  • 输出将被发送回替换脚本
  • 脚本的输出发送到屏幕

1 个答案:

答案 0 :(得分:2)

是。这是我为自己编写的东西,用于包装要求文件路径的旧命令行Fortran程序。它允许逃回到外壳,例如跑'ls'。这仅适用于一种方式,即拦截用户输入,然后将其传递给程序,但可以获得您想要的大部分内容。您可以根据自己的需要进行调整。

#!/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";
      }
   }
}