Search code examples
bashshellunixprocessread-eval-print-loop

Programmatically send commands to an interactive REPL from Bash?


Is it possible to programmatically enter some repl (say mongo), and programmatically interact with it? That is to say, can you do this programmatically:

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

All that does is:

  1. Login to the REPL with the mongo command. I know it's possible to do this somehow, I have seen it done to create interactive REPL's in the Node.js world. It would be helpful to know how to do this in bash directly.
  2. Once logged in, I typed db.collections, just exploring the REPL. This SO question is asking, can you do this programmatically? Like can you perhaps (a) create a child process/REPL from a bash script, and then (b) send it arbitrary messages like this db.collections, which it evaluates. (And can you get the response/output back).
  3. Programmatically log out of the REPL.

Is this possible?


Solution

  • You could write an expect script which will interactively input those commands for you. I'm not a regular expect user but I think it should look something like this:

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

    There are a lot of examples out there which should make it easy to create a minimal working example.