You cannot create
threads in typical shell scripts, but you can create any number of parallel
processes. The difference is that you need to communicate via files or pipes or some other
interprocess communication methods, as shell and environment variables are local to each process.
In Bash (
bash) and POSIX shells (
sh), you can run anything concurrently by adding
& after the command. The shell instance that started such
background jobs is the parent process, and the job itself is called the child process. To wait until all background jobs have finished, simply use the
wait shell command. (It will return when there are no more background jobs running.)
In almost all cases, the above suffices. The actual
job control support is a lot more versatile, if you were to need more fine-grained control; see the
Job Control section in the Bash Reference Manual for details. Job control options are more or less identical in Bash and POSIX shells.
Here is a Bash example to get you started:
Code:
#!/bin/bash
(
# Do something here.
# This is a subshell, so variables, working directory, et cetera
# are private to this part.
# If you need to save results to the 'main' script,
# use for example a (temporary) file.
echo 'Task 1 is going to sleep for five seconds.'
sleep 5
echo 'Task 1 is done.'
) &
(
# Do something here too.
# This part will be run concurrently with the above.
echo 'Task 2 is going to sleep for three seconds.'
sleep 3
echo 'Task 2 is done.'
) &
(
# Yes, you can have as many of these sections as you like.
echo 'Task 3 is going to sleep for four seconds.'
sleep 4
echo 'Task 3 is done.'
) &
# Okay, let us wait until all of the above tasks have completed.
echo 'The parent is going to wait until all tasks are done.'
wait
echo 'The parent is done.'