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.
- Using ampersand ‘&‘:
We append ‘&‘ at the end of the command to execute in the background.
./start-app.sh start &
- Controlling background job with ‘bg‘, ‘fg‘:
First, we execute command as normal.
Then use shortcut Ctrl+Z to pause the execution of command.
To run the stopped execution as the background job, type:
To see list of background job, type ‘jobs’.
To bring the recent background job to front, type:
or specify the id of particular execution:
To kill a job, type:
(%1 or %2 is id of job displayed when we type jobs).
- 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 &