D. Arnold D. Arnold - 1 year ago 182
Bash Question

How to create Multiple Threads in Bash Shell Script

I have a an array of arguments that will be utilized as such in the command for my shell script. I want to be able to do this

./runtests.sh -b firefox,chrome,ie

where each command here will start a separate thread (currently we are multithreading by opening multiple terminals and starting the commands there)

I have pushed the entered commands into an array:

if [[ $browser == *","* ]]; then
IFS=',' read -ra browserArray <<< "$browser"

Now I will have to start a separate thread (or process) while looping through array. Can someone guide me in the right direction? My guess in sudo code is something like

for (( c=0; c<${#browserArray}; c++ ))
startTests &

Am I on the right track?

Answer Source

That's not a thread, but a background process. They are similar but:

So, effectively we can say that threads and light weight processes are same.

The main difference between a light weight process (LWP) and a normal process is that LWPs share same address space and other resources like open files etc. As some resources are shared so these processes are considered to be light weight as compared to other normal processes and hence the name light weight processes.

NB: Redordered for clarity

What are Linux Processes, Threads, Light Weight Processes, and Process State

You can see the running background process using the jobs command. E.g.:

nick@nick-lt:~/test/npm-test$ sleep 10000 &
[1] 23648
nick@nick-lt:~/test/npm-test$ jobs
[1]+  Running    

You can bring them to the foreground using fg:

nick@nick-lt:~/test/npm-test$ fg 1
sleep 1000

where the cursor will wait until the sleep time has elapsed. You can pause the job when it's in the foreground (as in the scenario after fg 1) by pressing CTRL-Z (SIGTSTP), which gives something like this:

[1]+  Stopped                 sleep 1000

and resume it by typing:

bg 1    # Resumes in the background
fg 1    # Resumes in the foreground

and you can kill it by pressing CTRL-C (SIGINT) when it's in the foreground, which just ends the process, or through using the kill command with the % affix to the jobs ID:

kill %1 # Or kill <PID>

Onto your implementation:


for i in "${@}"; do
    case $i in

IFS=',' read -r -a SPLITBROWSERS <<< "$BROWSERS"

for browser in "${SPLITBROWSERS[@]}"
    echo "Running ${browser}..."
    $browser &

Can be called as:

./runtests.sh -b firefox,chrome,ie


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download