Running 5 commands in parallel in the background

Fedora version: Fedora WS 34
Shell : bash

I have 5 commands which I want to execute in parallel in the bash shell. So, I can run it in the background by adding an & at the end of each command like below

command1 &
command2 &
command3 &
command4 &
command5 &

I remember reading in the stack exchange that, in such a scenario, it is recommended to add a wait command in the end as shown below. I don’t have the URL for that post now.

But, I would like to know why is it good to have the wait builtin/command added at the end in this scenario. Anyone has any idea ?

command1 &
command2 &
command3 &
command4 &
command5 &

Welcome to ask fedora @koopman.

In Bash nothing is really parallel. The scripts are executed from top to bottom (serial). As Bash is a script Language, it needs to know when something went wrong. Such termination statuses will be used to make decisions like if / else etc.

And wait does the following:

wait --help

wait: wait [-fn] [-p var] [id …]
Wait for job completion and return exit status.

Waits for each process identified by an ID, which may be a process ID or a
job specification, and reports its termination status.  If ID is not
given, waits for all currently active child processes, and the return
status is zero.  If ID is a job specification, waits for all processes
in that job's pipeline.

If the -n option is supplied, waits for a single job from the list of IDs,
or, if no IDs are supplied, for the next job to complete and returns its
exit status.

If the -p option is supplied, the process or job identifier of the job
for which the exit status is returned is assigned to the variable VAR
named by the option argument. The variable will be unset initially, before
any assignment. This is useful only when the -n option is supplied.

If the -f option is supplied, and job control is enabled, waits for the
specified ID to terminate, instead of waiting for it to change status.

Exit Status:
Returns the status of the last ID; fails if ID is invalid or an invalid
option is given, or if -n is supplied and the shell has no unwaited-for

If you are doing this from the terminal, you don’t need the wait. If this is a shell script, and you don’t use the wait, what will happen is that your main script will terminate and your 5 backgrounded jobs will continue to run. In this situation, people usually put wait at the end of their shell scripts to wait for their child processes to finish before terminating the main script.