首页 > 解决方案 > 在后台从 Bash 脚本启动进程,然后将其带到前台

问题描述

以下是我拥有的一些代码的简化版本:

#!/bin/bash

myfile=file.txt
interactive_command > $myfile &
pid=$!

# Use tail to wait for the file to be populated
while read -r line; do
  first_output_line=$line
  break # we only need the first line
done < <(tail -f $file)
rm $file

# do stuff with $first_output_line and $pid
# ...
# bring `interactive_command` to foreground?

我想interactive_command在其第一行输出存储到变量后将其置于前台,以便用户可以通过调用此脚本与它进行交互。

但是,似乎 usingfg %1在脚本的上下文中不起作用,并且我不能fg与 PID 一起使用。有没有办法我可以做到这一点?

(另外,是否有更优雅的方式来捕获第一行输出,而不写入临时文件?)

标签: bashjob-control

解决方案


fg使用和的作业控制bg仅在交互式 shell 上可用(即在终端中键入命令时)。通常 shell 脚本在非交互式 shell 中运行(与默认情况下别名在 shell 脚本中不起作用的原因相同)

由于您已经将 PID 存储在变量中,因此将进程置于前台与等待它相同(请参阅Job Control Builtins)。例如你可以做

wait "$pid"

此外,您还拥有一个基本版本的coprocbash内置,它允许您获取从后台命令捕获的标准输出消息。它公开了存储在一个数组中的两个文件描述符,使用它们可以从标准输出读取输出或将输入馈送到其标准输入

coproc fdPair interactive_command 

语法通常是coproc <array-name> <cmd-to-bckgd>. 该数组由内置的文件描述符ID填充。如果没有明确使用变量,则将其填充在COPROC变量下。所以你的要求可以写成

coproc fdPair interactive_command 
IFS= read -r -u "${fdPair[0]}" firstLine
printf '%s\n' "$firstLine"

推荐阅读