Bash Job Control

Job control in Bash refers to the ability to manage and control the execution of multiple processes within a shell session. This includes tasks like running processes in the background, bringing them to the foreground, suspending, and terminating them.

Job Control Fundamentals

  1. Processes and Jobs: Every program you run in Bash is a process. Job control groups processes to manage them collectively. A single command or a pipeline of commands forms a job.
  2. Interactive Shells Only: Job control primarily works in interactive shells, where you're actively using the terminal. It's not directly usable in scripts.

Foreground and Background Execution

To run a command in the foreground, you simply type the command and press Enter.

$ command

To run a command in the background, append an ampersand (&) to the command.

$ command &

Viewing Jobs

The jobs command displays a list of jobs running in the background.

$ jobs

Foreground and Background Switching

To bring a background job to the foreground, use the fg command followed by the job number.

$ fg %1

To send a foreground job to the background, use the bg command followed by the job number.

$ bg %1

Suspending and Resuming Jobs

To suspend a foreground job, press Ctrl + Z. This stops the process and puts it in the background. To resume a suspended job in the background, use the bg command followed by the job number.

$ bg %1

Terminating Jobs

To terminate a job, use the kill command followed by the job number or process ID.

$ kill %1

Job Numbers

Each job is assigned a unique job number, which can be used to refer to the job in various commands.

Example:
$ sleep 300 # Run a command in the foreground (will sleep for 300 seconds) Ctrl + Z # Suspend the foreground job $ bg # Move the suspended job to the background $ jobs # View background jobs $ fg # Bring the background job to the foreground

In the example above, the sleep command is initially running in the foreground. After pressing Ctrl + Z, it is suspended, and the bg command moves it to the background. The jobs command then displays the list of background jobs. Finally, the fg command brings the background job back to the foreground.

Cautions:
  1. Avoid excessive background jobs, as they can consume resources and clutter your terminal.
  2. Remember that job control isn't directly usable in scripts.

Conclusion

Job control in Bash allows users to manage and control the execution of processes within a shell session. This includes running processes in the background, bringing them to the foreground, suspending, and terminating them using commands like bg, fg, jobs, and kill. The system assigns unique job numbers to each process, facilitating easy reference in job control commands.