Bash – Can the shell automatically tell me when a background process is complete

background-processbash

I am just trying to teach myself GNU/Linux-style commands and tools in the bash terminal on my Mac.

I want the terminal to automatically display when a background process is complete. There is no specific program I am running, but, for example:

sleep 10 &

How do I (or is it even possible to) have it automatically display in the command line when sleep is done. Or do I just have to check manually?

Best Answer

set +b


The default mode. In this mode, every time bash is about to print its prompt, it first checks to see whether any background jobs have stopped or terminated, and if so it prints notification messages before displaying the prompt.

set +b never corrupts the display, but it has its own problems. In particular, suppose you are testing a GUI program whose source code you're editing in a separate editor window. (Let's assume it's written in an interpreted language.) You might have a terminal window in which you keep typing the same command, myprogram &. Every time you make changes to the program and want to restart it, you close down the current instance of it, and repeat this command in your shell window. Now bash will launch the new instance of the program before printing the notification that the old one has finished - and because printing that notification is the moment at which the job number allocation gets reset, this also means that your job numbers will increase without bound unless you deliberately hit Return at a point when no background job is running. Eventually, one instance of your program will hang and you'll have to type kill %134, instead of the kill %1 you would prefer.


set -b


In this mode, when any background job stops or terminates, bash receives a SIGCHLD signal, and its signal handler displays the notification message immediately - even if bash is currently in the middle of waiting for a foreground process to complete.

set -b has no awareness of the state of the terminal, so its notifications are likely to corrupt the display of any full-screen application you might be running (such as a text editor or MUA). In particular, this mode cannot even interact sensibly with bash's own command-line editing! Try running sleep 1 & in this mode, and then immediately beginning to type a command line. You will find that when the notification is printed, you are left with the display in a somewhat non-obvious state.


Source of all this found here.