【问题标题】:Launch process from Bash script in the background, then bring it to foreground在后台从 Bash 脚本启动进程,然后将其带到前台
【发布时间】:2019-05-14 10:48:11
【问题描述】:

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

#!/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 一起使用。有没有办法可以做到这一点?

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

【问题讨论】:

  • 答案对你有用吗?
  • 抱歉,最近比较忙,感谢您的回答!我实际上已经在使用wait,它不太适合我的需求,因为它不允许与后台命令交互。不过,我还没有尝试过coproc,所以我会试一试!

标签: bash job-control


【解决方案1】:

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

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

wait "$pid"

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

coproc fdPair interactive_command 

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多