I'm currently working on an audit-script for a huge platform. In the main-script we use traps and in one of the traps I ask the user for clean up the files. The script has no output in standard output, so running the script in the bg is obvious.

When sending a SIGQUIT to the bg-job it stops, and I have to put it manually in the foreground with fg to get the prompt.

What I tried: I played around with set -m to active job control and put an fg into my trap-function.

With set -m my shell close after the script finished, without it I get debug-output, that my script doesn't have job control. Even with set -m, the job doesn't come into foreground.

For this, my questions are:

  • Is it possible to force a job to come into foreground at some point?
  • I know this is not the common way to use job-control inside a script. What is "best practise" for this?
  • Is job-control inside a script only for sub-shells/child-processes or can I use it to control the job I started?

Edit: as lcd047 suggested it is much more elegant to use screen or tmux, to keep the scripts clean and simple.


Is job-control inside a script only for sub-shells/child-processes or can I use it to control the job I started?

Yes. It's the parent shell that does the job control, you can't put the child process to foreground from within itself.

Edit: You can however still do it like this:

  • Child script:

    #! /bin/sh
    trap "kill -s USR1 $PPID" TTOU
    echo -n Cleanup?
    read yn </dev/tty
  • Parent script:

    #! /bin/sh
    trap "fg %1" USR1
    child &

This installs a signal handler for SIGTTOU in the child, and another signal handler for SIGUSR1 in the parent. When the child tries to output something to the terminal it receives a SIGTTOU. It then sends a SIGUSR1 to the parent, which in turn runs fg %1 and puts the child to foreground.

The above assumes %1 to be the child process. In practice you probably have a single process in background anyway.

  • absolutly solves my issue! Is it common to do like this or should I just find another solution in genereal without job-control? – quenia May 12 '15 at 10:26
  • 2
    It's probably not very common, and prone to subtle complications (and bugs). Personally I'd just run it in tmux or screen in a pane, and not bother with background. – lcd047 May 12 '15 at 10:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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