Bash: redirect input from 2 sources?

Viewed 117

I want to execute a Linux command in Bash with the input coming from a file or echo, and then switch back to standard input as if the command's input was not redirected.

So basically, I want to feed the first part from an interactive command with a predefined text, and as soon as that text is "consumed" I want to continue using the keyboard (stdin).

Some examples: Prefill editor and then continue typing manually

(echo blablabla; cat) | nano

Auto remove first file, then manually confirm removing second file

touch dummyfile1.txt; touch dummyfile2.txt
(echo y; cat) | rm -i dummyfile*.txt

Fill in password for dummyuser, and than let the user fill in the password for the zip file

(echo dummypassword; cat) | su dummyuser -c "unzip pwdprotectedfile.zip"

Here, the echo fills in the first part of the command, and then cat takes over to copy stdin to stdout to manually fill in the remaining part of whatever the command needs.

The (echo ; cat) method is the closest thing that (almost) works. But the problem here is that at the end an extra enter key press is needed to return to the command prompt.

How to do this properly without the extra key press needed?

The real situation I need this for is to run su -c somecommand, fill in the password automatically (from a secure source) and then let the user answers the questions asked by somecommand.

1 Answers

If your intent is to programmatically generate a content for the nano editor, it is as simple as telling nano to edit the standard input by specifying - as file name.

echo "blablabla" | nano -

Now consider that echo behaviour is not portable across shell versions, so prefer it printf '%s\n' "blablabla" for a single line of text.

To be courteous with the user, you can invoke his preferred editor as set in the EDITOR environment variable, with fall-back to vi if the EDITOR environment variable is not set.

printf '%s\n' "blablabla" | "${EDITOR:-vi}"

If you are using bash, you can replace piping printf with an here-string instead:

#!/usr/bin/env bash

"${EDITOR:-vi}" - <<<"blablabla"
Related