It is a common thing for software engineers of all sorts to log into a remote computer using ssh and work with a shell like bash, zsh etc. Often, they might need to work with multiple programs like a text editor, a database shell etc. in the remote computer. There are several ways to achieve this. One of the ways is to just open one ssh login shell for each program you want to run. But that is highly inefficient and inconvenient. Another solution would be to use a tool like tmux to multiplex your terminal. Tmux has its own advantages, and I highly recommend it if you are looking for advanced features. However, being an advanced tool, tmux has a learning curve. Plus, it is not always available as it does not come pre-installed in most operating systems. In this article, we are going to look into a set of commands which will allow us to run multiple program within the same shell. These commands are built into bash and are always available.
Sending a process to the background
While working in a shell, if you have ever accidentally pressed
Ctrl-Z you might have noticed that the program that you were working on disappears and some text like
+ Stopped shows up in the screen. What happens is that the program gets sent to the background and its execution is paused. The shell becomes free and you we can run other commands in it. To bring the program back to the foreground and resume its execution, just type
fg and press enter.
Listing all processes sent to the background
Once a process is sent to the background, you can start another program in the shell. This program can also be suspended by pressing
Ctrl-Z. Thus, we can send multiple programs to the background at the same time. To see a list of all programs in the background, we use the command
jobs. This gives us a list of all programs in the background with a number assigned to each one of them. This number can be passed to
fg command to bring the corresponding program to the foreground.
Making a process execute in the background
So far we have seen that processes sent to the background are alive but their execution is paused. What if we want to have a process running in the background. This is where the
bg command comes in. Any process which is in the suspended in the background can be made to execute in the background. Just like the
bg command can also accept a number obtained from the
jobs command and make the corresponding process resume execution in the background.