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

标签 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?

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

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

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

最佳答案

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

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

wait "$pid"

此外,您拥有的是 coproc bash built-in 的基本版本它允许您获取从后台命令捕获的标准输出消息。它公开存储在一个数组中的两个文件描述符,使用它们可以从 stdout 读取输出或将输入馈送到其 stdin
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"

关于bash - 在后台从 Bash 脚本启动进程,然后将其置于前台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56128713/

相关文章:

linux - Linux 中的作业控制 - 想要将控制权交还给终端

java - Hadoop作业控制

linux - 如何循环遍历 3 个文件,搜索特定字符串并使用 bash 将其与另一个文件中的字符串匹配

c - 搭建shell/BBS服务器推荐书籍

bash - 删除最终的 bash 脚本参数

c - C中fork的子进程是前台还是后台

Bash 等待立即终止?

json - mongoimport 错误处理

bash - 用 sed 替换更大部分中的一个单词?