如何捕获bash命令的输出,该命令会提示用户进行确认,而不会阻塞输出或命令

我需要捕获bash命令的输出,该命令会提示用户确认而不改变其流程。

我只知道两种捕获命令输出的方法:

- output=$(command)
- command > file

在两种情况下,整个过程都被阻塞,没有任何输出。

例如,不带--assume-yes:

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

由于命令尚未完成,我无法将输出打印回来。

有什么建议吗?

编辑1:用户必须能够回答提示。

编辑2:我使用破折号回答来完成bash script,允许用户从任何Debian / Ubuntu发行版中删除/清除所有过时的软件包(没有候选安装包)。

tou999999 回答:如何捕获bash命令的输出,该命令会提示用户进行确认,而不会阻塞输出或命令

要捕获正在等待提示的部分输出,可以在临时文件上使用尾部,如果需要,可以使用带有“ tee”的潜力使输出保持流动。这种方法的缺点是stderr需要与stdout绑定在一起,这使得很难区分两者(如果这是一个问题)

#! /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

没有一种通用的方法(从脚本中)告诉确切的程序何时提示输入。上面的代码查找提示字符串(“ continue?”),因此必须针对每个命令进行自定义。

本文链接:https://www.f2er.com/3122283.html

大家都在问