How to Run Linux Commands in the Background Like a Pro

As a Linux power user, running commands in the background is an essential skill for multitasking and working efficiently. Whether you need to keep long-running processes running after logging out or free up your terminal to do other work, sending a process to run in the background is easy with a few handy Linux tools.

In this comprehensive guide, we’ll explore five methods for running Linux commands in the background:

  1. Using the Ampersand (&)
  2. The bg command
  3. nohup
  4. disown
  5. tmux

I‘ll explain the basics of each approach, when you‘d use them, and how to manage background processes like a pro. Let‘s dive in!

Why Run Linux Commands in the Background?

Here are some of the top reasons why running Linux commands in the background comes in handy:

  • Multitask: Send processes to run in the background to free up your terminal for other work.
  • Persist after logout: Some background processes will continue running even if you log out or close the terminal.
  • Detach processes: Removing a process from the terminal‘s job control allows it to run independently in the background.
  • Remote sessions: Tools like tmux let you attach and re-attach remote sessions while background tasks run.

Running programs in the background gives Linux exceptional multitasking capabilities compared to other operating systems. It‘s a crucial technique for effectively leveraging the terminal.

1. Ampersand (&) Background Process

The simplest way to run a Linux command in the background is by adding the ampersand (&) operator after the command.

For example:

$ long_running_process &

This immediately executes long_running_process as a child process of the current shell, freeing up the terminal for you to run other commands.

Some key notes about the & operator:

  • The process will run in a subshell environment, with [stdin, stdout, stderr] attached to the terminal.
  • When the shell exits, the background process will be terminated.
  • Background processes started this way are jobs, so you can manage them with job control commands.

To demonstrate, here‘s a sleep command running in the foreground that locks up the terminal:

$ sleep 60
(terminal blocked for 60 seconds)

By adding the &, sleep runs in a subshell in the background, freeing up the terminal instantly:

$ sleep 60 &
$ echo "terminal unlocked!"
terminal unlocked!
$

The sleep process here is attached to the job control system and managed by the shell. We can view background jobs with the jobs command:

$ jobs
[1]+ Running                 sleep 60 &

And terminate the background job easily with kill:

$ kill %1
$ jobs
$

In practice, running quick one-off commands in the background with & is handy for avoiding blocking the terminal unnecessarily.

But for long-running persistent background processes, other tools like nohup and tmux tend to be more appropriate, as we‘ll see later.

2. bg – Background Job Control

The bg command sends a stopped job to run in the background. First I‘ll explain what that means, then demonstrate how to use bg.

Job control is a shell feature that lets you stop, restart, and background processes.

Processes started in the terminal are attached to the shell‘s job control system as jobs. Each job has a number ID shown in the output of the jobs command.

For example, running sleep without & attaches it to job control and prints the job ID:

$ sleep 60
[1]+ Stopped                 sleep 60
$ jobs
[1]+ Stopped                 sleep 60

We can now manage this sleep process as job 1.

The bg (background) command restarts job 1, running it in the background:

$ bg %1
[1]+ sleep 60 &
$ jobs
[1]+ Running                 sleep 60 &

Now sleep runs independently in a subshell, without blocking our terminal usage.

Some key points about bg:

  • Only works on jobs that have been stopped with CTRL + Z
  • Backgrounds the most recently stopped job by default
  • Jobs will terminate once the shell/session exits

In summary, bg lets you take command line programs attached to job control and push them to run asynchronously in the background instead.

3. nohup – Persistent Background Processes

The nohup (no hang up) command runs processes persistently in the background, immune to hangups that can disrupt background jobs running in subshells.

Here‘s an example starting a continuous ping that will run forever in the background, ignoring hang up signals:

$ nohup ping example.com &
$ nohup: appending output to ‘nohup.out‘
$ jobs
$

The key benefits of using nohup are:

  • Background process persists after user logs out
  • Immune to hangup signals from the terminal disconnecting
  • Output redirected to nohup.out file by default

This makes nohup ideal for long-running background tasks where you may log out while waiting for the job to complete.

For example, you could run nohup before SSHing out of a remote server, and rest assured the process will continue running after you disconnect.

nohup File Output

The standard output and errors of a nohup process are redirected to a file called nohup.out in the current working directory.

To demonstrate, first I‘ll run nohup sleep to background a job, then cat out the contents of nohup.out:

$ nohup sleep 10 &
appending output to nohup.out
$ cat nohup.out 
nohup: ignoring input
$

As you can see, the otherwise lost output from the backgrounded sleep command was captured to nohup.out.

You can control nohup output redirection as well, telling it explicitly what file to send output:

$ nohup sleep 20 &> my_output.log

So in summary:

  • nohup backgrounds processes + persists after logout
  • Redirects stdout/stderr to nohup.out
  • Output file controlled via redirection

This makes nohup very useful for remote server administration tasks!

4. disown – Detach Process from Terminal

The disown command detaches a running job from the shell‘s job control system, allowing it to run independent of the terminal state.

The difference compared to nohup is subtle.

While nohup backgrounds a process and ignores terminal hangups, the process is still managed as a job. So if you exit the shell session, the nohup‘ed jobs will terminate.

disown goes a step further, removing jobs from job control altogether. This allows the process to run in the absolute background until explicitly killed or the system reboots.

Here is an example demonstrating disown:

First I‘ll start top watching system resources with job control:

$ top
(Ctrl + Z to stop top and job control)
[1]+ Stopped                 top

Now top is stopped but managed as job 1. I‘ll background it with bg:

$ bg %1
[1]+ top &

Although backgrounded, top is still attached to the terminal as a job. When I exit the shell, top will terminate.

By disowning it from job control altogether, top persists after shell exit:

$ disown -h %1
$ exit
(shell session exits but top persists)

Some key disown properties:

  • Detaches jobs from job control
  • Jobs persist after shell/terminal closes
  • Process remains until explicitly killed

This technique comes in very handy when administering remote servers. I‘ll often disown monitoring processes before ending an SSH session to keep them running in the absolute background on the server.

5. tmux – Terminal Multiplexing in the Background

tmux is an incredibly powerful terminal multiplexer that lets you create persistent terminal sessions that run in the absolute background.

You can think of tmux like opening nested tabs or windows in your terminal, with each tab running a separate shell, isolated from the others. Processes running inside tmux will persist after you detach from the session.

Why use tmux?

  • Persist multiple long-running processes after detaching terminal
  • Attach and re-attach remote terminal sessions
  • Separate terminals for focused workflows

For servers and remote work, I rely heavily on tmux for running persistent monitoring, logging, and administrative background jobs that stay running no matter what happens to SSH connections.

Let‘s walk through a hands-on tmux tutorial to demonstrate the basics…

tmux Tutorial

I‘ll give an overview of how to start tmux, open windows, panes, and detach/re-attach sessions.

Note: Run tmux -V to check if tmux is installed on Linux. If not present, install tmux via your distro‘s package manager.

Start new session:

tmux new -s mysession

This launches tmux with session name "mysession"

New window:

Ctrl + b c  (c = new window)  

Split pane horizontally:

Ctrl + b " (vertical line splits pane)

Split pane vertically:

Ctrl + b %  (percent sign splits pane)   

Cycle panes:

Ctrl + b o (next pane)
Ctrl + b ; (previous pane)

Session commands:

Ctrl + b d (detach session - persists in background)
tmux attach  (re-attach session)
tmux list-session - lists saved sessions
tmux kill-session -t mysession (kill session) 

That just scratches the surface of what you can do with tmux!

It‘s an extremely versatile tool – once you grasp the basics of splitting panes and detaching/re-attaching sessions, you can do some really powerful things with terminal multiplexing.

Some examples of handy uses for server administration:

  • Monitoring logs or metrics in one pane, app console in another
  • Group projects workflows into isolated sessions
  • "Recurring session" saved for regular terminal tasks

Overall tmux helps me be exponentially more efficient when doing remote work by persisting sessions cleanly in the background.

Top Tips for Running Linux Commands in the Background

Here are some best practice tips for running processes in the background:

  • Use & for quick backgrounding without persistence
  • Leverage nohup for long running remote processes
  • disown jobs that must run until explicitly killed
  • Learn tmux for advanced terminal multiplexing sessions
  • Redirect stdout/stderr to capture background output
  • Use jobs to list and fg to foreground processes
  • Kill runaway background processes with kill %[job_id]

Job control is a powerful bash feature – mastering various methods for backgrounding processes unlocks next-level Linux terminal productivity.

Understanding &, bg, nohup, disown and tmux gives you precise control over running processes in the shell.

Summary: Running Linux Commands in the Background

As we‘ve explored, Linux offers flexible tools for running processes as jobs in the background, detached from the terminal entirely, and within persistent tmux sessions.

Here‘s a quick cheatsheet of the backgrounding methods we covered:

Method Persists After Logout Detached from Terminal Output Redirection
& No No (job control) Tied to terminal
bg No Yes (subshell) Tied to terminal
nohup Yes No (job control) To file
disown Yes Yes Tied to terminal
tmux Yes Yes Within tmux pane

I encourage you to practice using these different techniques for runningLinux commands in the background.

Mastering job control and background processes will seriously improve your terminal productivity!

Let me know if you have any other background process tips or tricks. Thanks for reading!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *