8 Top Methods to Run Linux Commands in Background
Running Linux commands in the background is helpful for various reasons; this capability allows you to execute multiple commands simultaneously in a terminal session without waiting for one command to complete. This feature is particularly beneficial when dealing with lengthy data processing or file transfers, which are time-consuming processes. It results in time savings and frees up the terminal for other tasks. This is the very thing we’ve often wished for – a way not to be forced to wait for a process to complete for a long time before moving on to other tasks.
Running Linux commands in the background is an efficient practice for managing servers to execute services and daemons (such as web servers, databases, and other system services), automating tasks at specific times or intervals, and remote sessions, even in case of session disconnection.
So, if you’re buying a Linux VPS for the efficiency of your tasks, read this article to the end to become an expert in optimal server and remote session management, as well as multitasking without wasting time. This article teaches 8 methods for running Linux commands in the background. By reading this article, you will learn how to run a command in the background, keep long-running processes running after closing the shell session, and focus on your other tasks simultaneously.
1. Using ‘&’ (Ampersand)
The simplest method for running Linux commands in the background is to append an ‘&’ (ampersand) at the end of a command:
command &
The ampersand symbol instructs the shell to run the command in the background separately while still making the shell available for running other processes. For example, when you launch a text editor in a Linux terminal, the shell becomes unusable for running other processes until the text editor is closed. By typing the ampersand symbol at the end of the command, the text editor runs in the background, and you can use the shell to initiate other processes. For example:
nano &
Output:
[1] 2781
As you can see, this command provides the shell job ID and process ID as output.
verifying the running of Background Processes
After running a process in the background, you can use the “jobs
” command to check the background processes’ status in the current shell session to verify the execution of the background process:
jobs -l
This command prints the job number, process ID, job state, and the command that started the job.
Bringing a background process to the foreground
Now, if you want to move the background process to the foreground, run the”fg
” command:
fg
If multiple processes are running in the background, to bring a specific process to the foreground, you should use the fg command along with the job ID or process ID associated with the process. For example, to bring the “nano” process to the foreground that you previously moved to the background back, you should run the following command:
fg 1%
Or
fg 2781
Terminating the background process
To terminate a process running in the background, the “kill
” command can be of assistance. For this purpose, execute the “kill” command along with the process ID in the Linux terminal:
kill -9 2781
As a result, the process was terminated with a Process ID (PID) of 2781.
2. Using ‘nohup’
If you want to ensure the execution of a process even in the event of disconnection, logging out of the system, or the termination of a terminal session, use the “nohup
” (no hang up) command. The nohup tool prevents the command from hangup signals, ensuring it continues to run. The basic syntax for using the nohup command to run Linux commands in the background is as follows:
nohup command &
Output:
nohup: ignoring input and appending output to 'nohup.out'
For example:
nohup ping OperaVPS.com &
The command output is, by default, redirected to a log file (nohup.out) in the current directory.
The “nohup” command distinguishes itself from other methods due to its advantages, such as not terminating the process when closing the terminal session or logging out of the system. It is one of the best ways to run complex and long-running Linux processes in the background.
To verify the execution of the desired process in the background, even after the terminal session has ended, you can use the “jobs
” command:
jobs
You can also confirm the saving of the output of the “nohup” command in the nohup.out log file located in the current directory or the $HOME directory by running the following command:
cat nohup.out
3. Using ‘bg’
You might not have anticipated in some cases that a command could occupy your time for an extended period, and as a result, you find yourself stuck in the execution of a long-running process that was already running. To escape from these frustrating situations and attend to your other tasks, you can use the “bg
” command to move the process from the foreground to the background. To achieve this, first, stop the process running in the foreground by pressing “Ctrl+Z,” and then run the bg command to send the process to the background:
bg
As a result, the output of the bg command indicates the continuation of the process in the background. To ensure the execution of the process in the background, you can execute the “jobs
” command.
Furthermore, to bring a process from the background to the foreground, you can use the “fg” command followed by the job ID or process ID.
4. Using ‘disown’
Another method to keep a process running after the shell exits is to use the “disown” command. When you run a command in the background, the disown command is used to remove the command from the shell’s job table while keeping the process running in the background. This way, the process won’t receive signals from the terminal, allowing users to continue executing a process even after closing the terminal. To achieve this, use the following commands:
command &
disown
If more than one process is running in the background, use the “%” symbol and job ID at the end of the command:
disown %1
To ensure the removal of a job from the shell’s job table, run the following command:
jobs -l
If you didn’t receive any output, you can ensure that the process is not dependent on the shell. However, to confirm the execution of the process outside of the shell, you can use the “ps aux
” command:
ps aux | grep [process ID]
The output of the previous command lists all processes, including disowned ones, and then provides details about a specific process ID.
5. Using System Redirects
Redirects, after sending a command to the background, suppress standard output and standard error streams (stdout and stderr messages) and redirect them to a specific log file. As a result, after processing the command, the terminal is freed. The syntax is:
command > output.log 2>&1 &
As a result, the output of the command and any errors are directed to the “output.log” file, and a signal is sent to the Bash shell to continue executing the command in the background.
If you want to discard the output of the command and its error streams, you can redirect the output to “/dev/null” by running the following command:
command > /dev/null 2>&1 &
6. Using ‘screen’ or ‘tmux’
As we’ve discussed previously, you are aware that Screen is a terminal multiplexer software for the Linux operating system that allows the management of multiple terminal sessions within a single terminal window. Using “screen” in Linux is an efficient tool for tasks that require running multiple command-line programs or managing remote sessions. Processes running in “Screen” are preserved even in the event of disconnection, and their windows remain unaffected by disconnects and interruptions.
In addition to “screen,” there is also “tmux,” which provides a way to run commands in virtual terminal sessions that can be detached and reattached as needed. The “tmux” tool allows users to manage multiple tasks simultaneously, create new windows and split them (using “Ctrl+b” followed by the “%” key), and easily switch between panes(using “Ctrl+b” followed by the Right or Left Arrow key or Up or Down Arrow keys). As a result, you have the flexibility to execute different commands without interference in each window and perform multiple tasks. “tmux” is a modern replacement for “screen” (GNU screen) and, like “screen,” allows users to launch persistent sessions that don’t terminate even when the terminal is closed. Running Linux commands in the background through tools like “screen” and “tmux” is much simpler and more efficient.
7. Using ‘at’ and ‘batch’
With the “at” and “batch” commands, you can schedule your tasks for execution at a specific time or during times of low system load. You can plan to run a script containing commands that will be executed as background services in turn. To do this, first create a Bash script (a .sh file) and place the commands you want to run as background services within it using your preferred text editor. For example, create a file named “my_background_script.sh” and add the commands that are to be executed in the background to it:
bash
#!/bin/bash
echo "Running my background command..."
some_command_to_run_in_background &
echo "Background command completed.
Replace “some_command_to_run_in_background” with the commands you intend to run in the background.
Then, use the “chmod
” command to make the script executable:
chmod +x my_background_script.sh
Next, open the terminal and use the “at” command to schedule the execution of the Bash script for a specific time. For example, schedule the script to run in one hour:
at -f /path/to/my_background_script.sh now + 1 hour
List the scheduled tasks by running the “atq
” command to ensure that the bash script is scheduled:
atq
As a result, the Bash script is executed in the background at the specified time. You can monitor the status of running processes by checking log files or using tools like “ps.”
Note: Using the “at
” command may require the necessary permissions, and ensure the script includes all the environment variables and paths required for a successful background command execution.
8. Using ‘systemd’
Another method for running commands as background services is creating a systemd service unit. This approach is well-suited for managing daemons and system services. Systemd is the default init system in many modern Linux distributions, and it can be used for managing and running background commands in Linux. To do this, you first need to create a Systemd Service Unit file. Create a custom service unit file for your command. For example, create a simple unit file for a hypothetical background service (e.g., “my-background-service.service”) in the “/etc/systemd/system/” directory or “/etc/systemd/user/” directory:
sudo nano /etc/systemd/system/my-background-service.service
Specify the service unit in the file as follows:
[Unit]
Description=My Background Service
[Service]
Type=simple
ExecStart=/path/to/your/command
Restart=always
User=your_username
Group=your_groupname
[Install]
WantedBy=multi-user.target
Replace “/path/to/your/command” with the full path to the command or script you intend to run as a background service. You can also define the user and group for which you want the service to run.
After creating the service unit file, enable and start it:
sudo systemctl enable my-background-service
sudo systemctl start my-background-service
As a result, the service will start immediately during system boot.
To check the service’s status, run the following command:
systemctl status my-background-service
You can manage different services using the following commands:
- In order to terminate a service, type the following:
sudo systemctl stop my-background-service
- To disable the service from starting at boot, use the following command:
sudo systemctl disable my-background-service
Ultimately, by following this method, systemd takes control of your command, running it as a background service and making it easy to start, stop, and monitor the service.
Wrapping up
One of the most crucial skills when using Linux is the ability to work with Linux commands and interact with the Linux terminal. If you have weaknesses in terminal interaction, you may face difficulties performing tasks and waste a lot of time. This guide has provided 8 valuable methods for running Linux commands in the background, helping you learn how to efficiently manage multiple tasks simultaneously. By sending tasks to the background using various methods, services can continue to run in the background for an extended period without interfering with other processes, even when you close the terminal and end the shell session.
However, we recommend not leaving your services running in the background for extended periods, as in some cases, they can turn into zombie processes and lead to a slowdown of your system. Therefore, regularly monitor background processes.
We hope this article proves to be useful for Linux system administrators. If you have any questions or feedback, please feel free to share them in the comments section.