我可以有一个在后台运行的 (bash) shell 吗?

我可以有一个在后台运行的 (bash) shell 吗?

我正在尝试编写一个expect脚本,一旦启动,它将监视我的终端并在每次找到匹配项时运行命令。

这甚至可能吗expect?如果是这样,expect_background使用正确的东西吗?

编辑:为了清楚起见,我正在尝试expect从终端输出,而不是输入......

答案1

是的,您只需使用 bash 即可做到这一点:将标准输出重定向到一个tee进程,该进程可以在看到您的模式时执行某些操作。tee很好,因为它还将标准输出放在标准输出上。

exec 1> >(tee >(awk '/foobar/ {print "*** DING DING ***"}'))

这会将 stdout 发送到进程替换 1, tee,后者将其标准输入复制到 stdout 和进程替换 2(一个执行某些操作的 awk 脚本)。您可以将代码或脚本的路径放入内部进程替换中。

展示

$ echo this is foobar stuff
this is foobar stuff
$ exec 1> >(tee >(awk '/foobar/ {print "*** DING DING ***"}'))
$ date
Thu Mar 10 16:37:14 EST 2016
$ pwd
/home/jackman
$ echo this is foobar stuff
this is foobar stuff
*** DING DING ***

答案2

#!/usr/bin/env expect
#
# Adapted from autoexpect(1). Matches stuff from user.

if {[llength $argv] == 0} {
  send_user "Usage: $argv0 command \[cmd args...]\n"
  exit 64
}

match_max 100000
set userbuf ""

proc input {c} {
  global userbuf

  send -- $c
  append userbuf $c

  # if see this pattern in the input, execute command
  # NOTE may well muss up the terminal display, depending
  # on the output, etc.
  if {[regexp "echo.foo\r" $userbuf]} {
    system "uptime"
  # trim buffer between commands so not chewing up all the memory
  } elseif {[regexp "\r" $userbuf]} {
    set userbuf ""
  }
}

spawn -noecho $argv

interact {
  # match incoming characters, send to buffer builder (otherwise
  # if just "echo foo" here that input will vanish until expect
  # can run a command, or fails the match, which isn't nice.
  -re . { input $interact_out(0,string) }
  eof { return }
}

另一种方法更简单(但要注意 shell 回显)。

#!/usr/bin/env expect
#
# Also adapted from autoexpect(1).

if {[llength $argv] == 0} {
  send_user "Usage: $argv0 command \[cmd args...]\n"
  exit 64
}

match_max 100000

proc output {s} {
  send_user -raw -- $s

  # NOTE shells tend to echo commands as they are typed, which may
  # cause double-triggers depending on the expression being looked
  # for an what exactly is passed to this call from the echos.
  if {[regexp "foo" $s]} {
    system "uptime"
  }
}

spawn -noecho $argv

interact {
  -o -re .+ { output $interact_out(0,string) }
  eof { return }
}

相关内容