Saturday, 24 February 2018

linux - Force a backgrounded complex task to fg itself?


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).



Answer



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

No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...