[Linux] Execute commands as background job

When we execute a shell-script that need long time to run, we can send it to background job so that we can execute other tasks. For example, we need to execute an start-app.sh to start a web server, we can use one of the following method to run command as background job.

  1. Using ampersand ‘&‘:
    We append ‘&‘ at the end of the command to execute in the background.

    ./start-app.sh start &
  2. Controlling background job with ‘bg‘, ‘fg‘:
    First, we execute command as normal.

    ./start-app.sh start

    Then use shortcut Ctrl+Z to pause the execution of command.
    To run the stopped execution as the background job, type:

    bg

    To see list of background job, type ‘jobs’.
    To bring the recent background job to front, type:

    fg

    or specify the id of particular execution:

    fg %1

    To kill a job, type:

    kill %2

    (%1 or %2 is id of job displayed when we type jobs).

  3. Using ‘nohup‘:
    All method above will be killed when user is logout or session is over. To have a persistent execution of commands/scripts, we use ‘nohup‘.

    nohup ./start-app.sh start &

    To specify where the log will be written to, use the command below:

    nohup ./start-app.sh start > /my-dir/nohup.out &