bash - 在后台从 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 一起使用。有没有办法我可以做到这一点?
(另外,是否有更优雅的方式来捕获第一行输出,而不写入临时文件?)
解决方案
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"
推荐阅读
- php - 如何在 Yii 中渲染空网格表?
- spring - Spring(Boot)中文件上传的响应式流式处理方法
- mysql - 如何访问嵌套指针结构
- kotlin-coroutines - 如何链接协程流?
- java - 如何将值的字符串转换为数组?
- azure - 修改通过 OMS 代理收集的 CEF 日志的解析
- javascript - 如何将图片库从片段传递到另一个活动?
- amazon-web-services - 如何检查是否已配置 AWS X-Ray
- javascript - React Native - 警告:无法对未安装的组件执行 React 状态更新
- python - (范围(3),范围(3))ValueError:解包的值太多(预期2)