Bash – a practical example of using the suspend command in Bash

bashjob-controlprocess-management

suspend is a builtin command in Bash. When would you naturally use this command and find it useful?

Best Answer

Let's say you lack both GNU screen and tmux (and X11, and virtual consoles) but want to switch between a login shell and another interactive shell.

You would first login on the console, and then start a new shell, temporarily blocking the login shell. To get the login shell back to do some work there, you'd do suspend. Then you would fg to get the interactive shell back to continue with whatever it was you did there.

In fact, with job control, the login shell could spawn a number of interactive shells as background jobs that you could switch to with fg %1, fg %2 etc., but to get back to the login shell, you would need to use suspend unless you wanted to manually kill -s STOP $$.

Also note that Ctrl+Z at the prompt in an interactive shell won't suspend it.

EDIT: I initially had a long hypothetical section about the use of suspend in a script, but since the command requires job control and since non-interactive shells usually don't have job control, I deleted that section.


Deleted section with suspend replaced by kill -s STOP $$ (this really doesn't belong to the answer any more, but it may be interesting to others anyway):

Let's say you have a background process (a script) in a script, and that this background process at some stage needs to stop and wait for the parent process to tell it to go on. This could be so that the parent has time to extract and move files into place or something like that.

The child script would suspend (kill -s STOP $$), and the parent script would send a CONT signal to it when it was okay to continue.

It gives you the opportunity to implement a sort of synchronisation between a parent process and a child process (although very basic as the parent shell process more or less needs to guess that the child process is suspended, although this can be fixed by having the child trap CONT and not suspend if that signal is received too early).