Linux Scripts Running in the Background
This articles gives a brief explanation of running scripts in the background.
Foreground to Background
If you've started something in your session and it's captured the session, you can move it to the background by issuing the
ctrl+z bg commands.
ctrl+z: Stops the process. It doesn't kill it.
bg: "bg" stands for background. This sends the current process to the background and releases your current command prompt.
It's better to plan properly, but this is an easy way to switch from a foreground to background if you change your mind.
Run Scripts in the Background
A script can be run in the background by adding a "&" to the end of the script.
You should really decide what you want to do with any output from the script. It makes sense to either throw it away, or catch it in a logfile.
# Throw it away. /home/my_user/scripts/my_script.sh >> /dev/null 2>&1 & # Redirect to log file. /home/my_user/scripts/my_script.sh >> /home/my_user/scripts/logs/my_script.log 2>&1 &
If you capture it in a log file, you can keep an eye on it by tailing the log file.
tail -f /home/my_user/scripts/logs/my_script.log
The script can still be affected by hang-up signals. You can stop this by using the
nohup command. This will accept all standard output and standard error by default, but you can still use a custom log file.
# All output directed to nohup.out. nohup /home/my_user/scripts/my_script.sh & # All output captured by logfile. nohup /home/my_user/scripts/my_script.sh >> /home/my_user/scripts/logs/my_script.log 2>&1 &
Checking Background Jobs
jobs command lists the current background jobs and their state.
$ jobs + Running /home/my_user/scripts/my_script.sh >> /home/my_user/scripts/logs/my_script.log 2>&1 & $
You can bring a job to the foreground by issuing the
fg command for the job of interest.
$ fg 1
Once in the foreground, it's just like any other foreground process, and keeps hold of the shell until it completes.
For more information see:
Hope this helps. Regards Tim...