2009-08-08 24 views
0

有沒有辦法在交互式終端中的bash命令解析輸入和輸出到達屏幕之前?我想也許是.bashrc中的一些東西,但我是使用bash的新手。解析終端輸出/輸入的方法? (.bashrc?)

例如:

  • 我鍵入 「ls /家庭/富/酒吧/」
  • 這被通過一個腳本,用於替換 '欄' 的所有實例與 '蛋'
  • 過去了「 LS /家庭/富/蛋/」被執行
  • 輸出被髮送回替換腳本
  • 腳本的輸出發送到屏幕

回答

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"; 
     } 
    } 
} 
+0

有沒有辦法像箭頭鍵和歷史記錄一樣使用腳本? – Annan 2009-08-08 15:21:18

+0

不是我所知道的。這些是shell內建的,並且假設shell是交互式運行的(在這種情況下它不是)。如果你需要比這更多的功能,那麼你真的在編寫你自己的shell - 這不像聽起來那麼難。見例如http://linuxgazette.net/111/ramankutty.html – 2009-08-08 18:20:20