Linux runs commands in the background in two ways:

  1. CMD & : running in the background, turn off the terminal will stop running
  2. Nohup CMD & : running in the background. Turning off the terminal will not stop running

Method 1: CMD &

  • The CMD & implementation lets commands run in the background. But don’t put commands with user interaction in the background, where they will wait for user input. Commands running in the background also output the results to the console, which can be redirected to a file if not needed. Both standard output and error output will be redirected to a file called cmd.out using the following command:

    cmd  >  cmd.out  2>&1  &
  • After the success of the executed command, displays a process, it can be used to monitor (ps – ef | grep process) or kill process (kill 9) processes.

Option 2: NOHUP CMD &

  • With Method 1, when we close the terminal, the command will stop running. Plus nohup can shut down the terminal without stopping the command. The general form of this command is:

    nohup command &
  • By default, all output from this command is redirected to the nohup.out file. You can also specify the output file as nohupcmd.out using the following command:

    nohup command > nohupcmd.out 2>&1 &
  • Nohup can only ensure that the command is running in the background if it exits the terminal normally with the exit command. Background commands will also stop when a terminal abnormally exits.

Other relevant commands:

  • Ctrl + Z: Put the command in the background and pause it.
  • Jobs: To see how many commands are currently running in the background, -l displays the PID of all tasks.
  • FG: Put background commands back in the foreground to run.
  • Bg: Put nested commands in the background to run.

The fg and bg commands can be specified as fg(bg) %jobid. %jobid is the serial number (not pid) of the background command found through jobs.