How to Run Linux Commands in Background [8 Effective Methods]

TL;DR

Try any of the following methods to run Linux commands in background:

  1. & Operator: Use the & operator to run commands like sleep 60 & in the background, allowing continued use of the terminal.
  2. nohup Command: Use nohup followed by your command and &, as in nohup ./my_script.sh &, to run processes persistently even after logout.
  3. bg Command: Use bg to resume stopped processes in the background, enabling you to continue other tasks without interruption.

If you use a Linux Terminal and want to keep working while commands run in the background, you’ve come to the right place. In this article, I’ll show you eight easy ways to run Linux commands in background. This means you can start a task and then keep on working without waiting for the first one to finish. I’ll look at simple methods like using the & operator and also explore more advanced tools like screen, tmux, and systemd. By the end of this guide, you’ll know how to keep your work flowing smoothly without pausing for commands to complete.

How to Run Linux Commands in Background on Linux?

To run Linux commands in background, use the ampersand (&) at the end of your command for quick tasks like sleep 60 &. For tasks that must continue after logout, prefix the command with nohup and add & at the end, as in nohup ./my_script.sh &. If a running process needs to be moved to the background, pause it with Ctrl+Z then use bg to resume it in the background, freeing up your Terminal.

Here are the detailed steps for each method to run Linux commands in background:

1. & Operator

The & operator in Linux is the simplest way to run a command in the background. It’s best suited for quick tasks that don’t require monitoring or reconnecting later. Using & allows you to continue using the Terminal for other tasks without waiting for the first command to complete. Follow these steps:

  1. Open your Terminal.
open terminal
  1. Type your command in the Terminal. Add an ampersand (&) at the end of the command.
$ sleep 60 &
  1. Press Enter. The command will execute in the background, and you’ll get the control of the Terminal immediately, along with the job number and process ID.
using operator to run the command in background
  1. Continue with other tasks in the Terminal without waiting for the background command to finish.

2. nohup Command

nohup, standing for no hang up, is used to run a command persistently in the background, even after logging out from the system. It’s ideal for long-running processes that need to continue running without interruption, regardless of the user’s session status. Here is how to do it:

  1. Access your command prompt and run the command with nohup at the beginning and & at the end.
$ nohup ./my_script.sh &

The command will start executing. The output that would normally go to the Terminal is sent to nohup.out by default.

using nohup command to run the process in background
  1. Close the Terminal or log out. The process will continue running in the background.

3. Using screen

screen is a powerful tool that allows you to manage multiple Terminal sessions from a single window. It’s useful for running processes that you might want to come back to, offering the flexibility to disconnect and reconnect without interrupting the running process. Here is the step-by-step guide: Follow these steps to to run the command in the background:

  1. Launch your Terminal and start a new screen session. Run the following command: 
$ screen -S session_name

Replace session_name with your session name.

starting new session using screen command
  1. Detach from the screen session by pressing Ctrl-a then d. Your process continues to run in the background.
starting a process in new screen then detach from it
  1. Reattach to your session whenever you need by typing:
$ screen -r session_name

This command will reattach you to the named session, allowing you to check on your process.

reattaching to the session

4. tmux Command

tmux is similar to screen but offers an enhanced user interface and more customization options. It is perfect for users who need to manage multiple sessions and easily switch between them. Here are the steps to do it:

  1. Open your Terminal and start a new tmux session. Execute the following command:
$ tmux new -s my_session

Replace session_name with your session name.

creating new tmux session
  1. Detach from the tmux session by pressing Ctrl-b then d.
running a process in tmux new session and detach it
  1. Reattach to the session when needed with:
$ tmux attach -t my_session

This command brings you back to your tmux session, where your process is running.

reattaching to tmux session

5. Utilizing systemd Services

Using systemd for running background processes is the most robust method. It is ideal for services that should start at boot time and be managed systematically using Linux’s service management capabilities. Here is the step-by-step guide:

  1. Access your Terminal and create a systemd service file by running the following command:
sudo nano /etc/systemd/system/my_service.service
creating a new systemd service file
  1. Edit the service file:
[Unit]
Description=My Background Service
[Service]
ExecStart=/path/to/your/script
[Install]
WantedBy=multi-user.target

Replace path/to/your/script with the actual path/

editing systemd service file in nano editor
  1. Reload the systemd manager configuration by typing:
$ sudo systemctl daemon-reload

This command updates systemd’s understanding of service files.

reloading systemd manager configuration
  1. Enable the service to start at boot by executing the following command:
$ sudo systemctl enable my_service.service

This command enables the service to start automatically at system boot.

enable service to start at boot
  1. Start the service immediately by entering the following command:
sudo $ systemctl start my_service.service

This command starts the service right away without needing to reboot.

starting the service immediately

6. disown Command

This method allows you to run a command in the background and then remove it from the shell’s job table, ensuring it continues running even if you close the shell session. Follow these steps to use the disown command to run the command in the background:

  1. In your Terminal, run your command followed by & to send it to the background:
command &

Replace the command with the actual command you want to run.

starting a process
  1. Disown the command:
disown

This removes the command from the shell’s job table, allowing it to continue running in the background even if you close the shell.

allowing the process to run in background

7. at Command

The at command schedules a command to be run at a specific time, making it useful for executing tasks at a later point. Here is how to use this command:

  1. Use echo to specify the command you want to run and pipe it into at with the desired time. For example, to run a command in 1 minute:
echo "command" | at now + 1 minute

Replace the command with the actual command you want to run.

scheduling command to run on specific time

8. bg Command

The bg command is a handy tool that allows you to resume a stopped process in the background. Here’s how to use it:

  1. If a process is currently in the foreground, stop it by pressing Ctrl+Z.
stopping the foreground process
  1. Resume the process in the background by running the command:
bg

It will resume the stopped process in the background.

resuming the process in background

How to Show Background Processes on Linux?

To show background processes in Linux, you can use the jobs command. This command lists the jobs (background processes) that are running or stopped in the current shell session. Here’s how you can use it:

  1. Open your command window and to list all background processes, simply type:
jobs

It will list all background processes in the current shell session.

listing all background jobs
  1. If you have multiple background processes, each job is assigned a job number. You can specify a particular job number to see its status:
jobs %job_number

Replace %job_number with the specific job number you want to check.

viewing speciific job

Optimizing Background Process Performance in Linux

Managing background processes efficiently is crucial for maintaining system performance and stability. By implementing best practices, you can ensure smoother and more efficient operation of your systems. Here are eight best practices to help you optimize these processes for better performance.

  • ๐Ÿ” Monitor Resource Usage: Regularly check how much CPU and memory your processes are using with tools like top or htop. This can help you spot processes that are using a lot of resources so you can adjust their settings or improve their efficiency. Keeping an eye on resources helps prevent overload and keeps your system running smoothly.
  • โฒ๏ธ Prioritize Processes: Use the nice and renice commands to adjust the priority of your processes. Assign higher priorities to critical tasks to ensure they get more CPU time. This approach helps important processes to run faster and more efficiently, which can be crucial in a multi-user environment or when running time-sensitive applications.
  • ๐Ÿ”„ Use Control Groups (cgroups): Set up control groups (cgroups) to manage how much resources (like CPU time, system memory, network bandwidth) each process can use. This helps in fair resource allocation and prevents any single process from taking too much control, which can degrade performance for others.
  • ๐Ÿ”ง Optimize Code: Examine your scripts and applications to make sure they are as efficient as possible. Look for ways to streamline operations, reduce unnecessary data processing, and avoid extensive logging where it’s not needed. Simple optimizations can lead to significant improvements in performance, especially for processes that run frequently or continuously.
  • ๐Ÿ’พ Manage I/O Scheduling: For processes that perform a lot of input/output operations, use the ionice command to set their I/O priority. This is especially important for systems where disk access speed is a bottleneck. Prioritizing critical I/O tasks can reduce wait times and speed up overall system performance.
  • ๐Ÿ”„ Regularly Update Software: Ensure that your system and all installed applications are up-to-date. Developers continuously improve their software, often optimizing performance and resource usage in updates. Regular updates can also protect against security vulnerabilities that might be exploited to launch resource-draining malware.
  • ๐Ÿš€ Use Appropriate Tools for Background Execution: Based on your specific needs, select the best tool for running your background processes. Screen or tmux are excellent for interactive tasks that might need to be revisited. For processes that need to run uninterrupted over long periods, consider using systemd or nohup for better reliability.
  • ๐Ÿ”’ Secure Processes: Run background processes with the minimum necessary privileges to both enhance security and performance. Creating dedicated user accounts for specific services limits potential damage from security breaches and ensures that services don’t use more resources than they truly need.

In a Nutshell

In this article, I’ve shared eight different methods to run Linux commands in background. Whether you’re applying the simple & operator for quick tasks or using the more robust systemd for ongoing services, these techniques are crucial for keeping your Terminal free while multitasking. Remember, implementing best practices like regular monitoring and prioritizing tasks will greatly enhance your system’s performance and stability.

If you want to enhance your understanding of Linux, I suggest exploring into topics such as how to create a systemd service to master setting up services that run in the background. Also, learning to use bash set x offers valuable debugging insights for background tasks. For handling multiple processes, explore how to detach a session in Tmux. These guides will enhance your ability to effectively manage Linux systems.

Frequently Asked Questions

  1. What is an & Operator?

    The & operator in programming and scripting contexts, especially within Unix-like operating systems such as Linux, is used to run a process in the background. When appended to a command in a terminal, it instructs the shell to execute the command but immediately return control to the user, allowing further commands to be entered and processed without waiting for the completion of the background task. This operator is particularly useful for running processes that take a long time to finish or do not require immediate supervision.

  2. How can I list all background processes started by my user?

    To list all background processes initiated by your user, you can use the ps command combined with grep to filter out your user’s processes. Run ps -u yourusername -o pid,cmd,state in the Terminal. This command displays process IDs, commands, and their states, highlighting any background activities.

  3. What should I do if a background process becomes unresponsive?

    If a background process becomes unresponsive, you can try to terminate it using the kill command followed by the process ID. If it’s stubborn, use kill -9 [PID] to forcefully stop it. Always check the process ID with the ps command to avoid terminating the wrong process.

  4. How do I bring a background process back to the foreground?

    To bring a background process to the foreground, first use the jobs command to display all background jobs with their job numbers. Then, use fg %jobnumber to move the desired job to the foreground. For example, fg %1 would bring the first listed job back into the foreground

  5. What happens to background processes when I log out?

    When you log out, any background processes not disassociated from your session typically receive a hangup signal and terminate. To prevent this, use nohup before the command when starting a process, or use the disown command after starting a process to detach it from the Terminal session.

Ojash

Author

Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

Akshat

Reviewer

Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, heโ€™s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

Share this article
Shareable URL
Prev Post

The Easiest Way to Enable Automatic Updates on Ubuntu

Next Post

How to Implement Docker Restart Policies? [4 Simple Restart Policies]

Read next