How to Run Linux Commands in the Background
Running Linux commands in the background is a powerful feature that allows users to multitask and save time. Instead of having to wait for a command to finish before moving on to the next one, background commands can run simultaneously, allowing you to focus on other tasks in the meantime. In this article, we will go over how to run Linux commands in the background and some useful techniques.
Starting a Process in the Background
To start a process in the background, use the command syntax: command &. The & at the end tells Linux to execute the command in the background.
For example, to run the command top in the background, you can run:
top &
The output will not be visible in the terminal, and you’ll get a process ID (PID) that you can use to manipulate the process, such as to send signals to it or to stop it. This is useful whenever you need to run a command that could take a long time to complete, or when you want to avoid waiting for the command to finish.
Another way to run a command in the background is to use the nohup command. This command lets you run a command that will keep running even after you have logged out from the system. Here is the syntax:
nohup command &
For example, to run the command sleep 5 in the background:
nohup sleep 5 &
If for some reason you need to stop a command running in the background, you can use a combination of the kill command and the PID of the process you want to stop. For example, to stop the process with the PID 1234, you can use the following command:
kill 1234
Viewing and Managing Background Processes
To view the list of processes running in the background, use the jobs command. This command will output a list of all the processes running in the current shell session. The jobs command should give you a list of each background job along with its job number in square brackets.
jobs
To bring a background process back to the foreground, use the fg command followed by the job number. This command will bring the process back to the terminal, where you can interact with it. For example, to bring the first job in the background to the foreground, use:
fg 1
Similarly, you can send a process to the background by using the bg command followed by the job number. For example, to send the first job to the background, use:
bg 1