How to capture the output of a bash command which prompts for a user's confirmation without blocking the output nor the command

I need to capture the output of a bash command which prompts for a user's confirmation without altering its flow.

I know only 2 ways to capture a command output:

- output=$(command)
- command > file

In both cases, the whole process is blocked without any output.

For instance, without --assume-yes:

output=$(apt purge 2>&1 some_package)

I cannot print the output back because the command is not done yet.

Any suggestion?

Edit 1: The user must be able to answer the prompt.

EDIT 2: I used dash-o's answer to complete a bash script allowing a user to remove/purge all obsolete packages (which have no installation candidate) from any Debian/Ubuntu distribution.

Upvotes: 1

Views: 1110

Answers (1)

dash-o
dash-o

Reputation: 14452

To capture partial output from that is waiting for a prompt, one can use a tail on temporary file, potentiality with 'tee' to keep the output flowing if needed. The downside of this approach is that stderr need to be tied with stdout, making it hard to tell between the two (if this is an issue)

#! /bin/bash

log=/path/to/log-file
echo > $log
(
  while ! grep -q -F 'continue?' $log ; do sleep 2 ; done ; 
  output=$(<$log) 
  echo do-something "$output"
) &
# Run command with output to terminal
apt purge 2>&1 some_package | tee -a $log

# If output to terminal not needed, replace above command with
apt purge 2>&1 some_package > $log

There is no generic way to tell (from a script) when exactly a program prompts for input. The above code looks for the prompt string ('continue?'), so this will have to be customized per command.

Upvotes: 1

Related Questions