Linux: Scripts (bash script) Running in the Background

This articles gives a brief explanation of running bash scripts or scripts in the background. Applies to all linux distributions: Centos, AlmaLinux OS, Rocky Linux, Ubuntu…

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. Please ctr+z out

/my_dir/my_script_file.sh &

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.
/my_dir/my_script_file.sh >> /dev/null 2>&1 &

# Redirect to log file.
/my_dir/my_script_file.sh >> /my_dir/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 /my_dir/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 /my_dir/my_script_file.sh &

# All output captured by logfile.
nohup /my_dir/my_script_file.sh >> /my_dir/my_script_file.log 2>&1 &

Checking Background Jobs

The jobs command lists the current background jobs and their state.

$ jobs
[1]+  Running   /my_dir/my_script_file.sh >> /my_dir/my_script_file.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.