以编程方式从 Bash 向交互式 REPL 发送命令?

Programmatically send commands to an interactive REPL from Bash?

是否可以以编程方式输入一些 repl(比如 mongo),并以编程方式与之交互?也就是说,您可以通过编程方式执行此操作吗:

$ mongo
MongoDB shell version: 2.4.8
connecting to: test
> db.collections
test.collections
> exit
bye

所做的只是:

  1. 使用mongo命令登录REPL。我知道可以以某种方式做到这一点,我已经看到 create interactive REPL's in the Node.js world 做到了。直接在 bash 中了解如何执行此操作会很有帮助。
  2. 登录后,我输入 db.collections,只是探索 REPL。这个 SO 问题是在问,你能以编程方式做 this 吗?就像你可以 (a) 从 bash 脚本创建一个子 process/REPL,然后 (b) 向它发送像这样的任意消息 db.collections,它会对其进行评估。 (你能把 response/output 找回来吗)。
  3. 以编程方式注销 REPL。

这可能吗?

您可以编写一个 expect 脚本,它将以交互方式为您输入这些命令。我不是一个普通的 expect 用户,但我认为它应该看起来像这样:

#!/usr/bin/expect
mongo
set timeout 10
expect "MongoDB shell version: 2.4.8"
send "db.collections"
expect "test.collections"
send exit

那里有很多示例,应该可以轻松创建一个最小的工作示例。