Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux pipe with multiple programs asking for user input

Tags:

linux

bash

pipe

I wonder how to create a pipe

program 1 | ... | program N

where multiple of the programs ask for user input. The problem is that | starts the programs in parallel and thus they start reading from the terminal in parallel.

For such cases it would be useful to have a pipe | that starts program (i+1) only after program i has produced some output.

Edit:

Example:

cat /dev/sda | bzip2 | gpg -c | ssh user@host 'cat > backup'

Here both gpg -c as well as ssh ask for a password.

A workaround for this particular example would be the creation of ssh key pairs, but this is not possible on every system, and I was wondering whether there is a general solution. Also gpg allows for the passphrase to be passed as command line argument, but this is not suggested for security reasons.

like image 875
Joerg Endrullis Avatar asked Aug 02 '12 22:08

Joerg Endrullis


2 Answers

You can use this construction:

(read a; echo "$a"; cat) > file

For example:

$ (read a; echo "$a"; echo cat is started > /dev/stderr; cat) > file
1
cat is started
2
3

Here 1, 2 and 3 were entered from keyboard; cat is started was written by echo.

Contents of file after execution of the command:

$ cat file
1
2
3
like image 169
Igor Chubin Avatar answered Sep 18 '22 14:09

Igor Chubin


I am now using:

#!/bin/bash
sudo echo "I am root!"
sudo cat /dev/disk0 | bzip2 | gpg -c | (read -n 1 a; (echo -n "$a"; cat) | ssh user@host 'cat > backup')

The first sudo will prevent the second from asking the password again. As suggested above, the read postpones the starting of ssh. I used -n 1 for read since I don't want to wait for newline, and -n for echo to surpress the newline.

like image 36
Joerg Endrullis Avatar answered Sep 20 '22 14:09

Joerg Endrullis