This guide will introduce you to Bash multi-threaded coding basics.

What Ismulti-threaded programming?

As far as the user is concerned, a single thread was executing a single sleep of one second.

The main page of the Homepage homelab dashboard with services running on it.

In the second line, we have two one-second sleep commands.

Normally, one would terminate a command by using a semicolon (;).

Doing so would execute the command and only then proceed to the next command listed behind the semicolon.

Terminal window showing the manual page for the Mutt email client on Linux

The||is the opposite of&&and will execute the second command only if the first command failed.

Additionally,Bash Process Termination Hacksmay be of interest.

As we can see ourdoneoutput shows in 1.005 seconds and thus the twosleep 1commands must have run simultaneously.

Article image

Aleksey Mnogosmyslov/Shutterstock.com

In essence, one may think about multi-threaded coding in Bash as starting several background threads.

It was rather the (sub)shell which was started when./rest.shwas executed.

Let’s change our script by addingjobsinside the script.

(Last command) A simple two thread one-line command which will run two sleep processes in parallel, one in the background

We can also see their PID’s (Process Identifiers).

These PIDs are very important when it comes to handling and managing background processes.

After 10 seconds, our first thread exists, and we are notified of the same.

Running two sleep threads in parallel, with one in the background, using a subshell

Wrapping up

In this article we explored Bash multi-threaded scripting basics.

We introduced the background process operator (&) using some easy-to-follow examples showing both single and multi-threadedsleepcommands.

We also explored thejobscommand to see running background threads/processes.

Running five parallel sleep threads in the background from a script

If you enjoyed reading this article, have a look at ourBash Process Termination Hacksarticle.

Adding jobs command in the script

Quering the PID (Process ID) of the last background process to be started using ${!}

Article image