How can I pipe initial input into process which will then be interactive?

Chris Stratton picture Chris Stratton · Apr 30, 2011 · Viewed 24.4k times · Source

I'd like to be able to inject an initial command into the launching of an interactive process, so that I can do something like this:

echo "initial command" | INSERT_MAGIC_HERE some_tool

tool> initial command 

[result of initial command] 

tool> [now I type an interactive command]

What doesn't work:

  • Just piping the initial command in doesn't work, as this results in stdin not being connected to the terminal

  • Writing to /dev/pts/[number] sends the output to the terminal, not input to the process as if it were from the terminal

What would but with disadvantages:

  • Make a command which forks a child, writes to its stdin and then forwards everything from its own stdin. Downside - terminal control things (like line vs character mode) won't work. Maybe I could do something with proxying of pseudo terminals?

  • Make a modified version of xterm (I'm launching one for this task anyway) with a command line option to inject additional commands after encountering a desired prompt string. Ugly.

  • Make a modified version of the tool I'm trying to run so that it accepts an initial command on the command line. Breaks the standard installation.

(The tool of current interest, incidentally, is android's adb shell - I want to open an interactive shell on the phone, run a command automatically, and then have an interactive session)

Answer

caf picture caf · May 2, 2011

You don't need to write a new tool to forward stdin - one has already been written (cat):

(echo "initial command" && cat) | some_tool

This does have the downside of connecting a pipe to some_tool, not a terminal.