Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start background process from shellscript then bring back to foreground later

I'm trying to make a shell script that does the following:

  • Start program x
  • While x is running execute some commands, for example:

    echo "blabla" >> ~/blabla.txt
    
  • After the execution of those commands program x should be running in the foreground, so that it can take user input.

So far I have:

~/x &
echo "blabla" >> ~/blabla.txt

However, I don't know how to move x back to the foreground. This is all called from a shell script so I don't know the job number of x to move to the foreground.

Note: everything has to be automated, no user interaction with the shell script should be needed.

Any suggestions are welcome :)

like image 880
Maricruzz Avatar asked Mar 02 '14 22:03

Maricruzz


People also ask

How do you run a process in background and bring it to foreground?

To bring the background process back, use the command 'fg'. Now if you simply use fg, it will bring the last process in the background job queue to the foreground.

Which command is used to bring a process from background to foreground?

The command fg %1 will bring the first background job to the foreground.

How do you brings the most recent job to foreground?

You can use the fg command to bring a background job to the foreground. Note: The foreground job occupies the shell until the job is completed, suspended, or stopped and placed into the background. Note: When you place a stopped job either in the foreground or background, the job restarts.


1 Answers

Although absolutely don't understand why someone may need such script, and I'm sure than exists more elegant and more better/correct solution - but ok - the next demostrating how:

The script what going to background (named as bgg)

#!/bin/bash
for i in $(seq 10)
do
    echo "bg: $i"
    sleep 1
done
read -p 'BGG enter something:' -r data
echo "$0 got: $data"

the main script (main.sh)

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

run the ./main.sh - and the result will be something like

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
like image 190
jm666 Avatar answered Sep 28 '22 06:09

jm666