Easy way to queue a job in the terminal

How to use background jobs to quickly queue a job after a running command
programming
system
Published

April 29, 2022

There is a small trick I love to use when running long commands in my terminal.

To run a job in the background, you can append & to the end of it. But what if you just started running a command, and you now realize you wanted to queue another command after it? Since you forgot to add &, it’s now running in the foreground in your terminal and it’s not easy to queue another job after it. Well, here is how to do it:

  1. You run your first command forgetting to add the & at the end
$ for i in {1..5}; do sleep 1; done
  1. You use CTRL + Z to pause that job and put it in the background. You should see
> [1]  + 93657 suspended  sleep 1
  1. You use fg && [new command] in order to put that job back to the foreground and queue another job to it.
$ fg && echo 'see!?'
> [1]  + 93657 continued  sleep 1
> see!?

Using the jobs feature

This is using the foreground/background job feature of the terminal. Here is a more detailed tutorial.

To summarize the few command I use: - CTRL + Z to put a job in the background - jobs to have a look at all the jobs - fg to put the last bakgrounded process back to the foreground - fg %2 to put another job back to the foreground - kill %2 to kill job number 2