从shellscript启动后台进程,然后稍后返回前台

从shellscript启动后台进程,然后稍后返回前台,shell,background-process,Shell,Background Process,我正在尝试制作一个shell脚本,该脚本执行以下操作: 启动程序x 当x运行时,执行一些命令,例如: echo "blabla" >> ~/blabla.txt 在执行这些命令之后,程序x应该在前台运行,以便它可以接受用户输入 到目前为止,我已经: ~/x & echo "blabla" >> ~/blabla.txt 但是,我不知道如何将x移回前景。这都是从shell脚本调用的,所以我不知道要移动到前台的x的作业号 注意:一切都必须自动化,不需要用户与

我正在尝试制作一个shell脚本,该脚本执行以下操作:

  • 启动程序x
  • 当x运行时,执行一些命令,例如:

    echo "blabla" >> ~/blabla.txt
    
  • 在执行这些命令之后,程序x应该在前台运行,以便它可以接受用户输入

到目前为止,我已经:

~/x &
echo "blabla" >> ~/blabla.txt
但是,我不知道如何将x移回前景。这都是从shell脚本调用的,所以我不知道要移动到前台的x的作业号

注意:一切都必须自动化,不需要用户与shell脚本交互


欢迎您提出任何建议:)

您可以使用
fg
将最后一个后台进程带到前台

尽管绝对不理解为什么有人可能需要这样的脚本,而且我相信比现有的解决方案更优雅、更好/正确-但没问题-下一步演示如何:

脚本将要转到后台(命名为
bgg

主脚本(
main.sh

运行
/main.sh
-结果如下

Sending bgg to background - will cycle 10 secs
Some commands
Mon Mar  3 00:04:57 CET 2014
main.sh - enter something:bg: 1
bg: 2
bg: 3
bg: 4
bg: 5
qqbg: 6
qqqqq
Main.sh got: ==qqqqqqq==
Backgroung job number: 1
Now sleeping 3 sec
bg: 7
bg: 8
bg: 9
Bringing 1 to foreground - wait until the BG job will read
./bgg
bg: 10
BGG enter something:wwwwwww
./bgg got: wwwwwww

如果程序x请求用户输入,尽管程序x在后台运行,它仍应显示在终端上。
set -m   #this is important

echo "Sending script bgg to background - will cycle 10 secs"
./bgg & 2>/dev/null

echo "Some commands"
date
read -r -p 'main.sh - enter something:' fgdata
echo "Main.sh got: ==$fgdata=="

jnum=$(jobs -l | grep " $! " | sed 's/\[\(.*\)\].*/\1/')
echo "Backgroung job number: $jnum"

echo "Now sleeping 3 sec"
sleep 3
echo "Bringing $jnum to foreground - wait until the BG job will read"
fg $jnum
Sending bgg to background - will cycle 10 secs
Some commands
Mon Mar  3 00:04:57 CET 2014
main.sh - enter something:bg: 1
bg: 2
bg: 3
bg: 4
bg: 5
qqbg: 6
qqqqq
Main.sh got: ==qqqqqqq==
Backgroung job number: 1
Now sleeping 3 sec
bg: 7
bg: 8
bg: 9
Bringing 1 to foreground - wait until the BG job will read
./bgg
bg: 10
BGG enter something:wwwwwww
./bgg got: wwwwwww