6 Effective Ways to Run Linux Commands in Background
6 Effective Ways to Run Linux Commands in Background

6 Effective Ways to Run Linux Commands in Background

For most Linux users, waiting for a command to finish before initiating a new one isn’t ideal.?

Whether you’re a seasoned pro or just a novice, working efficiently often means executing Linux commands in the background without having to wait for them to finish. This is often a critical requirement when you use scripts to automate server and user management.?

In this tutorial, we will guide you through several methods for executing Linux commands in the background.?

Let’s start with an overview of the idea of running processes in the background.

What’s the Idea of Running Processes in Background?

Running commands in the terminal typically occurs in the foreground. This requires users to wait for the completion of the command before they can issue the next.?

On the other hand, background execution allows commands to run concurrently with other tasks. This is an important benefit for commands that require some time to complete the execution. This makes the idea a great fit for scripts with long-running processes.?

Running Linux commands in the background is an efficient practice in managing server operations. This idea is used to run services and daemons (such as web servers, databases, and other system services), automate tasks at specific times or intervals, and run remote sessions, even if a session is disconnected.

There are several advantages of running commands in the background, including the following:

  • Multitasking
  • Support for long-running tasks
  • Higher Terminal availability
  • Detached execution

How to Run Linux Commands in Background

The best way of understanding the idea and the benefits of running commands in the background is to apply one or more of the following methods.?

Method #1: Use the Ampersand (&) Operator

Appending the ampersand (&) operator is the simplest and most straightforward method to run a command in the background.?

It instructs the shell to execute the command as a separate background process instead of the main terminal process.

To run a command in the background, add the ampersand symbol (&) at the end of a command in the following syntax:

# [command] &        

For instance, to initiate a background process for the Vim text editor, launch the terminal and type vim to initiate the command. Next, add an ampersand (&) at the end of the command.

# vim &        

Press Enter.?

vim-
vim-

The command will be executed in the background, and you’ll get control of the terminal immediately. You can see the job number and process ID. The number in square brackets ([1]) is the job ID, and the number following it (1698505) is the process ID.

By employing the ampersand operator, users can seamlessly execute and continue with other tasks in the terminal without waiting for the background command to finish.

Verification

To check the status of background processes in the current shell session, use the jobs command:

# jobs        
jobs
jobs

Bring a Background Process to the Foreground

Background processes typically run without requiring user input. However, there might be situations where a background process needs user input or interacts with other processes. Two common scenarios where you may need to bring a background process to the foreground is to monitor the output or handle an error during execution.?

You can bring a background process back to the foreground with the fg command:

# fg        

If you have multiple background processes, you need to use the fg command followed by the respective job ID or process ID to bring a specific process to the foreground.?

For instance, to bring the text editor Vim back to the foreground, use the job ID and append a percentage sign (%) to the command:

# fg 1%        
fg-1
fg-1

Method #2: Use bg

The bg command lets you shift a process from the foreground to the background. A common application of this command is to move the currently running foreground process to the background. This allows you to continue working in the terminal while the process executes in the background.

For instance, consider the scenario where the sudo apt update command is currently running and needs to transfer to the background. Here are the steps of the process:

sudo-apt-update
sudo-apt-update

Step #1: Suspend the Foreground Process

Press Ctrl + Z. This suspends the currently running foreground process.

Suspend-the-Foreground-Process
Suspend-the-Foreground-Process

Step #2: Continue the Process in the Background

Once the process is suspended, use the bg command to resume the process in the background.

# bg?

You can see a confirmation message in the terminal.

bg

Step #3: Verify the Change

You can verify if the process is running in the background by simply executing the jobs command without providing any arguments.

# jobs        

Method #3: Use nohu

The nohup utility is a powerful tool for running commands that continues the execution even after the terminal window closes or the user logs out. This is particularly useful for long-running processes that you wish to protect from interruptions. For this, the nohup command prevents the hangup signals from reaching the command.

By default, nohup redirects the output to a file named nohup.out.

The syntax of nohup is as follows:

# nohup [command] &        

Here,

nohup: Indicates the shell to run the following command even if the terminal session ends.

[command]: The command you want to execute in the background.

&: The ampersand (&) symbol instructs the shell to run the command in the background.

For instance, consider the situation where you need to ping a website in the background. You will use the following command:

# nohup ping (website) &        
nohup-ping
nohup-ping

The output would be similar to the following:

nohup: ignoring input and appending output to 'nohup.out'        

The command output, by default, is redirected to a log file nohup.out in the current directory.

Verification

To verify the execution of the desired process in the background, even after the terminal session has ended, run:

# jobs        
jobs-2
jobs-2

To 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, run:

# cat nohup.out

cat-nohup.out_
cat-nohup.out_

We recommend our tutorial on using the nohup command to run processes in the background. In this tutorial, we covered the process of background execution in detail.?

Method #4: System Redirects

While the previous methods focused on background execution, the system redirects control output and error messages. You can use redirection operators (> and >>) to send a command to the background while simultaneously redirecting its output and error messages to a log file.?

This frees up the terminal for other tasks and tracks the command’s activity.

The syntax of system redirects is as follows:

# [command] output.log 2>&1 &        

Here,

[command]: The command you want to run.

output.log: The log file to which the system redirects the output.

2>&1: Redirects errors to the same log file. It captures both standard output and error messages in the log file.

&: Instructs the system to run the command in the background.

For instance, consider the following scenario where you need to ping a website redswitches.com in the background and record its output (including any errors) in a log file named output.log. We will use system redirects in the following command syntax:

# ping redswitches.com > output.log 2>&1 &        
ping-redswitches.com_

Verification

To verify if the command is running in the background, run this command:

# jobs        
jobs-3
jobs-3

Once the execution is complete, the output and error messages generated by the ping command will be saved in the output.log file.

To confirm this, run:

# cat output.log        
cat-output.log_.png
cat-output.log_

Discard Output

If you no longer require the output of the command and its error streams, you can redirect the output to /dev/null by executing the following command:

# ping redswitches,com > /dev/null 2>&1 &        
ping-redswitchescom-2
ping-redswitchescom-2

This discards the output without saving it.

Method #5: Disown

Another method to keep a process running after the shell exits is to use the disown command.?

The disown command offers a way to detach a background process from the current shell session. This allows the process to continue even if the terminal session ends or the user logs out.?

To use disown to run commands in the background, follow the steps below.

Step #1: Start the Process in the Background

Start a process in the background using the ampersand (&) symbol.

For instance, to execute sudo apt update command in the background, run:

# sudo apt update &        

Step #2: Disown the Process

Execute the disown command without any arguments to detach the most recent background process from the shell.

# disown        

Step #3: Verify Detachment

Confirm the process is no longer linked to the shell or listed as a background process.

# jobs        

The shell will no longer manage the process if no output is displayed.

Step #4: Check Process Status

To confirm if the process is still running independently, use the ps command along with grep to search for the specific process ID:

# ps aux | grep [process ID]        

For instance, if the process ID is 2401, execute:

# ps aux | grep 2401        

The output confirms if the process, such as sudo apt update, is still active and operational.

Method #6: Tmux

Tmux (Terminal Multiplexer) is a powerful tool that allows Linux commands to run in the background while keeping them persistent across terminal sessions.?

It is particularly useful for maintaining long-running background commands and allows you to generate multiple virtual terminals within a single terminal window. While Tmux offers a robust solution, it has a steeper learning curve compared to the other methods.

The following steps demonstrate how to use Tmux to run commands in the background.?

Step #1: Start a New Tmux Session

Initiate a new Tmux session with this command:

# tmux new-session -s mysession        

Replace mysession with the name of your session.?

tmux-new-session-s-mysession

Step #2: Run Your Command

Within the newly created Tmux session, enter the command you wish to run in the background. For instance:

# ping redswitches.com        
ping-redswitches.com-3

Step #3: Detach From the Session

Press Ctrl + B followed by D to detach from the Tmux session while keeping the command running. This allows you to close your terminal window or work on other tasks.

Detach-From-the-Session
Detach-From-the-Session

Step #4: Manage Sessions

To reattach to the Tmux session later and view the output of the command, use:

# tmux attach-session -t mysession        
tmux-attach-session-t-mysession
tmux-attach-session-t-mysession

If you have multiple Tmux sessions, you can list them using:

# tmux ls        

To kill a specific Tmux session, use:

# tmux kill-session -t mysession        

Tmux provides a convenient way to manage long-running commands and maintain persistent sessions across terminal sessions.

Conclusion

Mastering the art of running Linux commands in the background is key for boosting productivity and efficiency in terminal-based workflows. Whether you use the ampersand (&), bg, nohup, the system redirects, disown, or Tmux, each method offers unique advantages for managing background processes effectively.

FAQs

Q. What is the nohup command used for?

The purpose of the nohup command is to run a command in a way that it won’t be affected by hangup signals. This means the command keeps running even if the terminal session ends or the user logs out.

Q. How does the screen session command work?

The screen session command creates a virtual terminal that allows users to run multiple processes simultaneously, even after disconnecting from the session.

Q. What is a foreground process?

A foreground process is a command or task that is executed in the active shell session and requires user input or interaction.

Q. How is the ampersand symbol used in Linux commands?

The ampersand symbol (&) at the end of a command implies the shell to run it in the background, freeing up the terminal for other tasks.

Q. What is the significance of the current directory in Linux?

The current directory refers to the directory in which the user is currently working, and it plays a crucial role in executing commands and accessing files.

Q. How can users view active processes in Linux?

Users can view active processes in Linux using commands such as ps aux or top, which provide a list of currently running processes.

Q. What is the purpose of the screen command?

A screen command is a powerful tool that allows users to create and manage multiple terminal sessions within a single SSH session, facilitating multitasking and remote server management.

Q. How can users run long-running processes in the background?

Long-running processes can be executed in the background by appending the ampersand symbol to the end of the command or using utilities like nohup or screen.

Q. What is the tmux command used for?

The tmux command works like the screen command. It helps you create and handle many terminal sessions, which is handy for multitasking and managing remote sessions.

Q. What do zombie processes signify in Linux?

Zombie processes are those that finished their job but haven’t been properly closed down, so they linger in the system’s process table. This usually happens due to incorrect termination of a process.

Q. How can users perform background tasks in Linux?

Background tasks can be performed by executing commands with the ampersand symbol (&) appended at the end, allowing them to run independently while users continue working in the foreground.

Q. How can users check the list of jobs in Linux?

Users can check the list of jobs in Linux using the jobs command, which displays the status of background tasks and their job IDs.

Q. What is the ping command used for?

The ping command verifies if a system is reachable on a network through sending and receiving messages.

要查看或添加评论,请登录

RedSwitches的更多文章

社区洞察

其他会员也浏览了