linux,

Run Linux Bash commands in background

Sep 26, 2021 · 2 mins read · Post a comment

If one thing can be annoying while working on remote Terminals on daily basis, that would be waiting for a command to finish. Wasting time on waiting commands to finish is resolvable in a couple of ways, including starting another Terminal session, and pushing or running commands in background, which will be the focus for today.

To begin with, we are going to use the ping command as an example through the tutorial. Although, leaving ping running in the background it’s not a good idea so, add the parameter -c to specify the number of packets send.

Prerequisites

  • Linux bash environment

run command in background

First things first, you could run any command in background by appending the & character.

ping devcoops.com &

Notes:

  • STDOUT and STDERR will still be printing in the foreground. This could be annoying as well, so the command you are looking for is:
    ping devcoops.com &>/dev/null &
    
  • The command will run in background until the Terminal session ends. We could fix this one too, by using the nohup command, which basically bypasses the SIGHUP signal.
    nohup ping devcoops.com &>/dev/null &
    

kill background running command

Step 1. grep the background command to find the process ID.

ps aux | grep ping*

Step 2. Kill the process.

kill -9 <process_ID>

Note(s): When you start the command in the background, it will print out the process ID.
Output:

[1] 29901

If you save the process ID somewhere, you could skip Step 1.

push running command in background

Step 1. Let’s say you start the ping command in the foreground. First, interrupt it by pressing control+z.
Expected output:

^Z
[1]+  Stopped                 ping devcoops.com

Step 2. List the processes in the current shell.

jobs -l

Output:

[1]+ 30704 Stopped                 ping devcoops.com

Step 3. Start the command in the background. For instance:

bg 1

bring background running command to foreground

Step 1. List the processes in the current shell.

jobs -l

Output:

[1]+ 30158 Running                nohup ping devcoops.com &>/dev/null &

Note(s): Keep in mind, the job ID value is 1 in the example above, and 30158 is the process ID.

Step 2. Once you find the job ID, bring the background job/command to the foreground. For instance:

fg 1

Conclusion

I’ve never been a fan of running commands in the background, and since we are living in almost the golden age of containers, IMO spinning up a container would be the best approach. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.