【问题标题】:A way to parse terminal output / input ? (.bashrc ?)一种解析终端输出/输入的方法? (.bashrc ?)
【发布时间】:2010-11-17 22:37:16
【问题描述】:

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

例如:

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

【问题讨论】:

    标签: linux bash command-line terminal


    【解决方案1】:

    是的。这是我为自己使用而编写的内容,用于包装要求文件路径的旧命令行 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";
          }
       }
    }
    

    【讨论】:

    • 有没有办法让箭头键和历史记录等内容与您的脚本一起使用?
    • 我不知道。这些是 shell 内置函数,并假设 shell 以交互方式运行(在这种情况下不是这样)。如果您想要比这更多的功能,那么您真的在考虑编写自己的外壳——这并不像听起来那么难。参见例如linuxgazette.net/111/ramankutty.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    相关资源
    最近更新 更多