Background a running process

Everyone knows and loves screen for running longtime scripts in the background without worrying that the ssh connection will drop and will have to run it again. Still, I have found myself many times in the situation where I started a process and needed to put it in the background and run something else on the console. Uff.. If only I started it with screen. But wait, there is hope. This quick tip will show how to put a process in the background and then start it back in foreground.

This works in bash and uses the ‘suspend’ key (CTRL+Z) and the bg - background and fg - foreground commands. Let’s say we were running an intensive rsync command, and are wanted to check if we still have the available space on the disk without opening a new ssh session (yes, I know):

rsync -ar server:/source/ /destination/
^Z
Stopped

Let it run in the background:

bg
[1] rsync -ar server:/source/ /destination/ &

Now we can run some other commands like du:

du -h

We can see the background process with ps or jobs:

jobs
[1]	Running		rsync -ar server:/source/ /destination/

And finally we can bring it back to foreground with fg:

fg

Note: this works only on the running ssh/bash session and it will be closed once you exit. Logout should warn about open/running jobs and that they will be lost if exit.

comments powered by Disqus