Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I will often run a simple monitoring task like the following:

(sleep 600 && ls -lh /path/to/files)&

Is it possible to have the process de-background itself part way in? For example, to grab the job id into $jobid (or similar), and then when the sleep finishes, do an fg $jobid?

This may require some more complex bash-fu, I am aware, but any solutions would be nice to see (especially if it's possible to only fg if there is no other interactive process running).

share|improve this question
up vote 1 down vote accepted

A non-interactive script has job control turned off by default, but you may enable it with set -m or set -o monitor. Here's an example script:

# turn on job control
set -o monitor

# start a background task
( sleep 10 && echo "slept 10 seconds" ) &

# do something else
sleep 5
echo "slept 5 seconds"

# bring the background task into the foreground
fg

echo "done"

Here's its output when run with tracing (bash -x script.sh):

+ set -o monitor
+ sleep 5
+ sleep 10
+ echo 'slept 5 seconds'
slept 5 seconds
+ fg
( sleep 10 && echo "slept 10 seconds" )
+ echo 'slept 10 seconds'
slept 10 seconds
+ echo done
done
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .