Wednesday, January 18, 2012

Jobs in Linux: Sending stuff to the Background

I use SSH to access my servers and often run commands that take a long time to finish. I could open another SSH window, but it's actually possible to multitask in the same command shell. The command you need to know are:

  • & (start job in background)
  • jobs (list all jobs)
  • fg (move a job to the foreground)
  • bg  (move a job to the background)
  • CTRL + Z (suspend the current job)
  • CTRL + C (kill the current job)
The & (ampersand) is used to run a command and send it to the background all in one go. (Example: sleep 100&) If you need to run a command and you know it will take a while, you can run it this way and you'll be able to run other jobs while it runs in the background. You can always see a list of your jobs and their job numbers by using the jobs command.

If you run a command and it's taking too long, you can press CTRL + Z (send it to the foreground AND pause it), then type bg [job number] to send it to the background and resume it. For example:
sleep 100 
[1]+  Stopped sleep 100
bg 1
[1]+  Running sleep 100
This will allow you to run other commands while sleep 100 continues running in the background.

If you need to suspend a job running in the background, you can use the fg [job number] command to bring it to the foreground (your active job) and press CTRL + Z to pause it. In the event that you need to kill a job, bring it to the foreground and use CTRL + C to kill it.

No comments:

Post a Comment