Often I see people waiting while their command is executing, impatiently tapping their desk until a file copy or command has finished.
They are often amazed when I show them that the Linux command line has a way of sending pending commands to the background, so you can continue on another task.
Below is a gif screencast which shows:
ping
to localhostctrl+z
sent to backgroundjobs
overview of all jobsbg
continue job in backgroundfg
return job to foreground
This is only a small portion of the capabilities of these commands. As always, the man
pages are a good starter if you’d like more information about what these commands can do more.
Advanced
The following tips might come in handy if you are looking for more streamlined task and job handling.
Redirect error to standard
If you run multiple jobs in the background, it is possible that you get errors directed at your standard terminal redirect standard and error to stdout. A quick way of redirecting error (stderr) to stdout is adding the following snippet at the end of your command.
2>&1
Output to both file and terminal
Tee
The command tee
allows you to both output to stdout and file, which means you are both logging and seeing what is happening.
Output to ping.log: ping localhost > ping.log Output to ping.log and terminal: ping localhost |tee -a ping.log
Keep processes running while no longer connected
Saving one of the best commands for last. nohup
. It means “no hang up”, and means that the process you ran does not stop after you disconnect. Hang up is coming from quite a long time ago when it meant dialling into a system.
nohup
is particularly handy if:
- You are remotely connecting to a machine
- and/or have long running processes
- and/or have a patchy connection
- and/or simply don’t want to wait for the process to finish
Notes about nohup
Our running process does not show up in jobs
, because it was started in a different session. Using nohup
means after hang up it is disconnected from whichever session in which it was started. I used pkill ping
, which stops everything which matches the search query, use with caution. Check with pgrep ping
or ps aux | grep ping
if you are doubting.
Super tip
What if a command you are running is taking longer than you expected, then you can nohup that command afterwards by using disown.
ctrl + z
to send the current process to background
bg
to continue running that process in the background
jobs
to determine that process its job number
disown -h [job number]
means the process will continue after your hangup
Tip: If you have only one process in the background, disown -a
disowns all processes. Even quicker!