Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

1 Answer 1

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.