LinuxCommandLibrary

fg

Move background process to foreground

TLDR

Bring most recently suspended or running background job to foreground

$ fg
copy

Bring a specific job to foreground (run jobs to find the job number)
$ fg %[job_number]
copy

SYNOPSIS

fg [%job_spec]

PARAMETERS

%job_spec
    An optional argument that specifies the job to bring to the foreground. If omitted, the most recently suspended job is used. Job specifications can be numbers (e.g., %1), strings matching the command that started the job (e.g., %sleep), or %%/%+ for the current job, or % - for the previous job.

DESCRIPTION

fg (foreground) is a shell built-in command used in Unix-like operating systems to resume the execution of a suspended or stopped job, bringing it back to the foreground.

When a command is running in the foreground, it has control of the terminal, meaning you can interact with it directly (e.g., input from keyboard, output to screen). Commands can be suspended by pressing Ctrl+Z, which sends a SIGTSTP signal to the process, stopping its execution and returning control to the shell.

The fg command allows you to select one of these suspended jobs and continue its execution in the foreground. This is crucial for interactive programs that require user input or real-time output. If no specific job is provided, fg typically operates on the most recently suspended job.

CAVEATS

The fg command is a shell built-in and not a standalone executable. Its behavior and availability depend on the specific shell (e.g., Bash, Zsh, Ksh) and require job control to be enabled in the shell. It can only operate on jobs that are currently suspended or stopped; it cannot bring a background job directly to the foreground if it's still running in the background without first stopping it (though some shells might implicitly stop it).

JOB SPECIFICATION DETAILS

When using fg with a job specification, you can refer to jobs in several ways:

  • %N: Refers to job number N (e.g., %1, %2).
  • %string: Refers to the job whose command line begins with string (e.g., %sleep if you started a sleep command).
  • %?string: Refers to the job whose command line contains string (e.g., %?long_script).
  • %% or %+: Refers to the current job (the most recently stopped or backgrounded job).
  • % -: Refers to the previous job.

HISTORY

Job control features, including the concept of foregrounding and backgrounding processes, were introduced to Unix-like systems as part of the C shell (csh) and later adopted by other major shells like Bourne Again Shell (bash), Zsh, and Ksh. The fg command has been a standard component of these job control mechanisms since their inception, providing essential process management capabilities to users.

SEE ALSO

bg(1), jobs(1), kill(1), disown(1), suspend(1)

Copied to clipboard