在后台从 Bash 脚本启动进程,然后将其置于前台

Dav*_*ley 5 bash job-control

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

#!/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?
Run Code Online (Sandbox Code Playgroud)

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

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

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

Ini*_*ian 4

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

由于您已经将 PID 存储在变量中,因此将进程置于前台与等待它相同(请参阅作业控制内置)。例如你可以这样做

wait "$pid"
Run Code Online (Sandbox Code Playgroud)

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

coproc fdPair interactive_command 
Run Code Online (Sandbox Code Playgroud)

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

coproc fdPair interactive_command 
IFS= read -r -u "${fdPair[0]}" firstLine
printf '%s\n' "$firstLine"
Run Code Online (Sandbox Code Playgroud)